如何在 JavaScript 循环中添加延迟? [英] How do I add a delay in a JavaScript loop?

查看:82
本文介绍了如何在 JavaScript 循环中添加延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to add a delay/sleep inside a while loop:

我是这样试的:

alert('hi');

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

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

Only the first scenario is true: after showing alert('hi'), it will be waiting for 3 seconds then alert('hello') will be displayed but then alert('hello') will be repeatedly constantly.

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

What I would like is that after alert('hello') is shown 3 seconds after alert('hi') then it needs to wait for 3 seconds for the second time alert('hello') and so on.

推荐答案

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

The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.

你可能想改用这样的东西:

You may want to use something like this instead:

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
    console.log('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

您也可以通过使用自调用函数将迭代次数作为参数传递来整理它:

You could also neaten it up, by using a self invoking function, passing the number of iterations as an argument:

(function myLoop(i) {
  setTimeout(function() {
    console.log('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

这篇关于如何在 JavaScript 循环中添加延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆