如何在for循环中使用setInterval函数
我正在尝试在给定可变项目列表的情况下运行多个计时器。代码看起来像这样:
var list = Array(...);
for(var x in list){
setInterval(function(){
list[x] += 10;
console.log(x + "=>" + list[x] + "\n");
}, 5 * 1000);
}
上面代码的问题是,唯一被更新的值是列表末尾的项目乘以列表中的项目数。
任何人都可以提供解决方案和一些解释,以便我知道为什么会出现这种情况?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是工作代码:
这里索引
i
存储在匿名函数中,以便它不会被连续循环覆盖。代码中的setInterval
函数仅保留对i
最后一个值的引用。Here is the working code:
Here the index
i
is stored in an anonymous function, so that it is not overwritten by consecutive loops.setInterval
function in your code keeps the reference only to the last value ofi
.因此,有几点:
setInterval()
的回调函数维护对x
的引用,而不是x< 的快照值/code> 因为它在每个特定迭代期间都存在。因此,当
x
在循环中发生更改时,它也会在每个回调函数中更新。for... in
用于枚举对象属性,并且在数组上使用时可能表现异常。setTimeout()
而不是setInterval()
。您可以通过向
setTimout()
提供附加参数来将参数传递给回调函数:数字将按值而不是引用传递。这是一个例子:
So, a few things:
setInterval()
maintains a reference tox
rather than the snapshot value ofx
as it existed during each particular iteration. So, asx
is changed in the loop, it's updated within each of the callback functions as well.for...in
is used to enumerate object properties and can behave unexpectedly when used on arrays.setTimeout()
rather thansetInterval()
.You can pass arguments to your callback function by supplying additional arguments to
setTimout()
:Numbers will be passed by value rather than reference. Here's an example:
您可以结合使用
forEach
和setTimeout
以按时间间隔循环遍历数组。You can combine
forEach
andsetTimeout
to loop over the array with the interval.您不必将 for 循环与
setInterval
语句一起使用。试试这个:You don't have to use a for cycle with the
setInterval
statement. Try this:我不知道如何使用 for 循环执行此操作,但这里的代码将按时间间隔打印出数组中的每个元素:
使用一些 jquery 在浏览器中显示它。
I don't know how to do this with a for loop but this code here will print out each element in an array at timed intervals:
Using a bit of jquery to show it in the browser.
请看看这个最简单的解决方案。它也适用于 forloop。它看起来像一个间隔,但它是每次迭代增加的超时。对于每次迭代,setTimeout 都会加倍。
Please look at this simplest solution. It does work with forloop too. It looks like an interval but it is a timeout increased for each iteration. For each iteration setTimeout doubles.
如果你有 JSON 数组和 jQuery,你可以使用:
If you have JSON array and jQuery included, you can use: