mercredi 21 octobre 2020

The effective way to combine multiple setinterval loop and if-statement

The following code gives me an error. Could you give me a hint about what is wrong with it? What is The effective way to combine multiple setinterval loop and if-statement in the following code? The purpose of this code that based on a and b value different actions will operate in a loop until the condition does not exist anymore, next to clear the setinterval I appreciate your time and help!

var number = 0;
var interval;

a=Math.random();
b=Math.random();
    
if(a>b) first();
if(a<b) second();
if(a=b) third();

function clear1() {
    if (interval !== undefined) {
        clearInterval(interval);
    }
    second();
}

//----------------------------------------------------------
first(){
interval = setInterval(function() {
 
    aa=Math.random();
    bb=Math.random();
    
if (aa>bb){
    console.log("a>b");
  

    number++;
}else{  // return;
clear1();}
}, 1000)
}


//----------------------------------------------------------
function clear2() {
    if (interval !== undefined) {
        clearInterval(interval);
    }
    second();
}


function second(){

interval = setInterval(function() {
 
    aa=Math.random();
    bb=Math.random();
    
if (aa<bb){
    console.log("a<b");
  

    number++;
}else{  // return;
clear2();}
}, 1000)
}


//----------------------------------------------------------
function clear3() {
    if (interval !== undefined) {
        clearInterval(interval);
    }
    third();
}



function third(){

interval = setInterval(function() {
 
    aa=Math.random();
    bb=Math.random();
    
if (aa=bb){
    console.log("a=b");
  

    number++;
}else{  // return;
clear3();}
}, 1000)
}
//-----------------------------------------------------------

first();

Aucun commentaire:

Enregistrer un commentaire