Search code examples
javascriptloopsif-statementlabeled-statements

Combine settimeout and label Loop and if statement


The following code is work as the following

while loop>> bring a and b values>> settimeout>> check the value by if-condition>> continue it true, else break;

This code with settimeout and is not working:

var number = 0;

start_position: while (true) {
  setTimeout(function() {
    console.log("Anything you want to print");
    var a = Math.random();
    var b = Math.random();
  }, 1000)

  number++;

  if (a > b) continue start_position;
  break;
}

This code without settimeout and is work just fine:

var number = 0;

start_position: while (true) {
  console.log("Anything you want to print");
  var a = Math.random();
  var b = Math.random();
  number++;

  if (a > b) continue start_position;
  break;
}


This is another way I tried too:

     var counter = 0;
    var i = setInterval(function(){
       
       
    var a=Math.random();
    var b=Math.random();
    console.log("a:",a);
    console.log("b:",b);
       
        counter++;
        if(a<b || a=b) {
            clearInterval(i);
        }
    }, 200);
     

Please, any suggestions?

Solution

  • Edit: This is more along the lines of what you want to accomplish. In your original case you had two problems A) The variables that you are checking are not in the correct function scopes and B) setTimeout functions get pushed into an event loop in javascript. Javascript will only run functions pushed into an event loop when the main thread is clear since javascript is single threaded. However because you have a while loop, that while loop will continue to run until it hits the break condition, never allowing your timeout function to be run, so it the while will run forever and the timeout function will never get run. This solution wraps the whole thing in a setInterval instead, setInterval will run periodically and then in this case is will clear itself when your condition is met.

    var number = 0;
    var interval;
    
    function clear() {
        if (interval !== undefined) {
            clearInterval(interval);
        }
        callFunctionYouWantToMoveTo();
    }
    
    interval = setInterval(function() {
        console.log("Anything you want to print");  
        a=Math.random();
        b=Math.random();
    
        number++;
    
        if (a>b) return;
    
        clear();
    }, 1000)