简体   繁体   English

如何在while循环中使setTimeout在JavaScript中按顺序执行?

[英]How to make setTimeout in while loop execute sequentially in JavaScript?

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. 请改用setInterval()

setTimeout executes the function once on a time out. setTimeout在超时时执行一次该函数。 setInterval executes the function repeatedly on and interval setInterval在on和interval上重复执行该函数

source 资源

To stop the interval, use clearInterval() 要停止间隔,请使用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; 如果你期望的是做x = x + 2; y = y + 1; x = x + 2; y = y + 1; in each iteration until x >= y then you can do like: 在每次迭代中直到x >= y然后你可以这样做:

 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: setTimeoutsetInterval之间的差异是:

You need to call setTimeout in your callback to keep it loop until it mets the stop condition. 您需要在回调中调用setTimeout以使其循环,直到它满足停止条件。 While setInterval just need to call once, you may have to use clearInterval to stop it to keep calling the callback . 虽然setInterval只需要调用一次,但您可能必须使用clearInterval来阻止它继续调用callback

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM