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);
}
1
  • 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? Commented Sep 15, 2015 at 8:42

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Could you please explain what's the difference between setInterval and setTimeout?
so when the condition of x<y is false, will the loop automatically break?
@Makudex I added the difference.
@tom.denka I updated my code to stop the loop with clearInterval.
@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.
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.