如何在for循环中使用setInterval函数 [英] How to use setInterval function within for loop

查看:2570
本文介绍了如何在for循环中使用setInterval函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行多个定时器给定一个变量项目列表。代码看起来像这样:

I'm trying to run multiple timers given a variable list of items. The code looks something like this:

var list = Array(...);

for(var x in list){
    setInterval(function(){
        list[x] += 10;
        console.log(x + "=>" + list[x] + "\n");
    }, 5 * 1000);
}

上述代码的问题是,唯一要更新的值是项目在列表的末尾,乘以列表中的项目数。

The problem with the above code is that the only value being updated is the item at the end of the list, multiplied by the number of items in the list.

任何人都可以提供解决方案和一些解释,所以我知道为什么它会这样做?

Can anyone offer a solution and some explanation so I know why it's behaving this way?

推荐答案

所以,有几件事:


  1. 最重要的是,你传递给 setInterval()保存对 x 的引用,而不是 x 因为它在每个特定迭代期间存在。因此, x 在循环中更改,它也在每个回调函数中更新。

  2. 此外, for ... in 用于枚举对象属性,并且可以在数组上使用时意外运行。 / li>
  3. 此外,我怀疑您确实希望 setTimeout() ,而不是 setInterval()

  1. Most importantly, the callback function you've passed to setInterval() maintains a reference to x rather than the snapshot value of x as it existed during each particular iteration. So, as x is changed in the loop, it's updated within each of the callback functions as well.
  2. Additionally, for...in is used to enumerate object properties and can behave unexpectedly when used on arrays.
  3. What's more, I suspect you really want setTimeout() rather than setInterval().

您可以将参数传递给回调函数通过向 setTimout()提供额外的参数:

You can pass arguments to your callback function by supplying additional arguments to setTimout():

var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);

以下是一个示例:

var list = [1,2,3,4];

for (var x = 0, ln = list.length; x < ln; x++) {
  setTimeout(function(y) {    
    console.log("%d => %d", y, list[y] += 10);
  }, x * 500, x); // we're passing x
}

幸运的是,按值而不是引用。

Luckily, numbers get passed by value rather than reference.

这篇关于如何在for循环中使用setInterval函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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