小编典典

如何在JavaScript循环中添加延迟?

javascript

我想在while循环内添加延迟/睡眠:

我这样尝试过:

alert('hi');

for(var start = 1; start < 10; start++) {
  setTimeout(function () {
    alert('hello');
  }, 3000);
}

只有第一种情况是正确的:显示后alert('hi'),它将等待3秒钟,然后alert('hello')显示,但随后alert('hello')将不断重复。

我想要的是在alert('hello')显示3秒之后显示出来,alert('hi')然后它需要第二次等待3秒alert('hello'),依此类推。


阅读 635

收藏
2020-04-22

共1个答案

小编典典

setTimeout()函数是非阻塞的,将立即返回。因此,您的循环将非常快速地迭代,并且将快速连续地发起3秒超时触发。这就是为什么您的第一个警报会在3秒钟后弹出,而其余所有警报都将连续不断地出现。

您可能要改用以下方式:

var i = 1;                     //  set your counter to 1

function myLoop () {           //  create a loop function
   setTimeout(function () {    //  call a 3s setTimeout when the loop is called
      alert('hello');          //  your code here
      i++;                     //  increment the counter
      if (i < 10) {            //  if the counter < 10, call the loop function
         myLoop();             //  ..  again which will trigger another 
      }                        //  ..  setTimeout()
   }, 3000)
}

myLoop();                      //  start the loop

您也可以通过使用自调用函数将迭代次数作为参数来修饰它:

(function myLoop (i) {          
   setTimeout(function () {   
      alert('hello');          //  your code here                
      if (--i) myLoop(i);      //  decrement i and call myLoop again if i > 0
   }, 3000)
})(10);                        //  pass the number of iterations as an argument
2020-04-22