首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在JavaScript循环中添加延迟?

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

Stack Overflow用户
提问于 2010-08-27 19:36:10
回答 28查看 593.5K关注 0票数 434

我想在while循环中添加一个延迟/休眠:

我是这样尝试的:

代码语言:javascript
复制
alert('hi');

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

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

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

EN

回答 28

Stack Overflow用户

回答已采纳

发布于 2010-08-27 19:38:39

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

您可能希望使用下面这样的内容:

代码语言:javascript
复制
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

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

代码语言:javascript
复制
(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

票数 882
EN

Stack Overflow用户

发布于 2010-08-27 19:40:23

尝试如下所示:

代码语言:javascript
复制
var i = 0, howManyTimes = 10;

function f() {
  console.log("hi");
  i++;
  if (i < howManyTimes) {
    setTimeout(f, 3000);
  }
}

f();

票数 77
EN

Stack Overflow用户

发布于 2017-04-05 14:56:47

这将会起作用

代码语言:javascript
复制
for (var i = 0; i < 10; i++) {
  (function(i) {
    setTimeout(function() { console.log(i); }, 100 * i);
  })(i);
}

试试这个小提琴:https://jsfiddle.net/wgdx8zqq/

票数 21
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3583724

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档