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);
}
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);
}
Use setInterval()
instead.
setTimeout
executes the function once on a time out.setInterval
executes the function repeatedly on and interval
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);
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
.