setTimeout() - 在for循环随机延迟 [英] setTimeout() - in for loop with random delay

查看:367
本文介绍了setTimeout() - 在for循环随机延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

JavaScript循环中的闭包 - 简单的实例


看到许多帖子谈论 setTimeout 和闭包,但我仍然不能传递一个简单的for循环计数器。

  for(i = 0; i <5; i ++){
setTimeout(function(){
console.log(i);
},Math.floor(Math.random()* 1000));
}

给予


5

5

5

5

5


< blockquote>

想要


0

1

2

3

4


出现什么问题? >
请不要火焰,我以为我理解了 setTimeout(),但显然不是。

解决方案

您可以使用闭包保留对循环中 i 当前值的引用:

  for(i = 0; i <5; i ++){
(function(i){
setTimeout (){
console.log(i);
},Math.floor(Math.random()* 1000));
})(i); //将当前值传递给自执行匿名函数
}

不太可能按顺序打印数字,因为您使用了随机超时(您可以使用 i * 1000 ,而不是按升序打印数字,相隔一秒)。 p>

这是工作示例


Possible Duplicate:
Javascript closure inside loops - simple practical example

Seen many posts talking about setTimeout and closures but I'm still not able to pass in a simple for loop counter.

for (i = 0; i < 5; i++) {
  setTimeout(function () {
    console.log(i);
  }, Math.floor(Math.random() * 1000));
}

Gives

5
5
5
5
5

Would like to have

0
1
2
3
4

What's wrong ?
Please don't flame, I thought I have understood the setTimeout() tale but apparently not.

解决方案

You can use a closure to keep a reference to the current value of i within the loop:

for (i = 0; i < 5; i++) {
    (function(i) {
        setTimeout(function () {
            console.log(i);
        }, Math.floor(Math.random() * 1000));
    })(i); //Pass current value into self-executing anonymous function
}​

However, this is unlikely to print the numbers in order since you use a random timeout (you could use i * 1000 instead to make the numbers print in ascending order, one second apart).

Here's a working example.

这篇关于setTimeout() - 在for循环随机延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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