4

How do I make the following simple while loop execute sequentially?

var x = 2;
var y = 10;
while (x<y) {
  x = x+2;
  setTimeout(function(){ y = y+1;
  }, 500);
}
tom.denka
  • 49
  • 5
  • Do you expect in each iteration `x = x + 2` and `y = y + 1`? Or you want to first add `x` to `10` then do `y = y + 1` with same counts of `x = x + 2`? – fuyushimoya Sep 15 '15 at 08:42

2 Answers2

6

Use setInterval() instead.

setTimeout executes the function once on a time out. setInterval executes the function repeatedly on and interval

source

To stop the interval, use clearInterval()

Example:

var x = 2,
    y = 10;
var loop = setInterval(function(){ 
    if(x<y) {
        x = x+2;
        y++;
    } else {
        clearInterval(loop);
    }
}, 500);
Community
  • 1
  • 1
R3tep
  • 12,512
  • 10
  • 48
  • 75
  • Could you please explain what's the difference between setInterval and setTimeout? – Makudex Sep 15 '15 at 08:41
  • so when the condition of x – tom.denka Sep 15 '15 at 08:42
  • @Makudex I added the difference. – R3tep Sep 15 '15 at 08:52
  • @tom.denka I updated my code to stop the loop with clearInterval. – R3tep Sep 15 '15 at 08:54
  • @R3tep *Why* does the question's code (presumably) not work? Is it, perhaps, related to [this](https://www.pluralsight.com/guides/introduction-to-asynchronous-javascript)? – nutty about natty May 14 '18 at 10:43
  • 1
    @nuttyaboutnatty The question code does not work because all setTimeouts are started at the same time. The while loop does not wait until the first setTiemeout is executed before starting the second iteration. It loops on all iterations and starts the setTimeout after. – R3tep May 14 '18 at 11:46
0

If what you expect is do x = x + 2; y = y + 1; in each iteration until x >= y then you can do like:

var x = 2;
var y = 10;
var func = function() {
  // While x is still smaller than y
  if (x < y) {
    x = x + 2;
    y = y + 1;
    console.log(x, y);
 
    // Register a timer to call self after 500ms if we still to loop.
    setTimeout(func, 500);
  }
};

// Manually start the function.
func();

The difference betweeen setTimeout and setInterval is:

You need to call setTimeout in your callback to keep it loop until it mets the stop condition. While setInterval just need to call once, you may have to use clearInterval to stop it to keep calling the callback.

fuyushimoya
  • 9,715
  • 3
  • 27
  • 34