Javascript 如何在for循环中使用setInterval函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7749090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use setInterval function within for loop
提问by hyleaus
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?
任何人都可以提供解决方案和一些解释,以便我知道它为什么会这样?
回答by canon
So, a few things:
所以,有几点:
- Most importantly, the callback function you've passed to
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. - Additionally,
for...in
is used to enumerate object properties and can behave unexpectedlywhen used on arrays. - What's more, I suspect you really want
setTimeout()
rather thansetInterval()
.
- 最重要的是,您传递给的回调函数
setInterval()
维护一个引用,x
而不是x
它在每个特定迭代期间存在的快照值。因此,随着x
循环中的变化,它也在每个回调函数中更新。 - 此外,
for...in
用于枚举对象属性,在数组上使用时可能会出现意外行为。 - 更重要的是,我怀疑你真的想要
setTimeout()
而不是setInterval()
.
You can pass arguments to your callback function by supplying additional arguments to setTimout()
:
您可以通过向以下参数提供附加参数来将参数传递给您的回调函数setTimout()
:
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
Numbers will be passed by value rather than reference. Here's an example:
数字将通过值而不是引用传递。下面是一个例子:
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
}
回答by Lapple
var list = [1, 2, 3, 4, 5];
for (var i = 0, len = list.length; i < len; i += 1) {
(function(i) {
setInterval(function() {
list[i] += 10;
console.log(i + "=>" + list[i] + "\n");
}, 5000)
})(i);
}
Here is the working code:
这是工作代码:
var list = [1, 2, 3, 4, 5];
for (var i = 0, len = list.length; i < len; i += 1) {
(function(i) {
setInterval(function() {
list[i] += 10;
console.log(i + "=>" + list[i] + "\n");
}, 5000)
})(i);
}
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 of i
.
这里索引i
存储在匿名函数中,因此它不会被连续循环覆盖。setInterval
代码中的函数仅保留对 的最后一个值的引用i
。
回答by uncleJessie
You don't have to use a for cycle with the setInterval
statement. Try this:
您不必在setInterval
语句中使用 for 循环。尝试这个:
var list = Array(...);
var x = 0;
setInterval(function() {
if (x < list.length;) {
list[x] += 10;
console.log(x+"=>"+list[x]);
}
else return;
x++;
}, 5000);
回答by Ryan Mc
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:
我不知道如何使用 for 循环执行此操作,但此处的代码将按时间间隔打印出数组中的每个元素:
function displayText(str) {
$('.demo').append($('<div>').text(str));
}
var i = 0;
var a = [12, 3, 45, 6, 7, 10];
function timedLoop() {
setTimeout(function () {
displayText(a[i]);
i++;
if(i < a.length) {
timedLoop();
}
}, 2000)
}
timedLoop();
Using a bit of jquery to show it in the browser.
使用一些 jquery 在浏览器中显示它。
回答by Taha A.
You can combine forEach
and setTimeout
to loop over the array with the interval.
您可以组合forEach
和setTimeout
以使用间隔循环遍历数组。
let modes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let interval = 1000; //one second
modes.forEach((mode, index) => {
setTimeout(() => {
console.log(mode)
}, index * interval)
})
回答by Atul Yadav
If you have JSON array and jQuery included, you can use:
如果包含 JSON 数组和 jQuery,则可以使用:
$.each(jsonArray, function(i, obj) {
setInterval( function() {
console.log(i+' '+obj);
}, 10);
});