JavaScript:用于超时的循环 [英] JavaScript : For loop with timeout
问题描述
我希望我的for循环不应该立即执行,而是在每次迭代后等待超时。例如:
I want that my for loop should not be executed at once, but wait for timeout after each iteration. For eg :
for(var i=0; i<10; i++) {
console.log(i);
//wait for 1000
}
我在堆栈上找到了很多解决方案 - 像这样溢出:
I found many solutions on stack-overflow like this one :
for (var i=0;i<=10;i++) {
(function(ind) {
setTimeout(function(){console.log(ind);}, 3000);
})(i);
}
但在所有实现中,循环最初等待3000毫秒并且然后立即执行整个 for
循环。有没有办法在等待1000毫秒后调用每个迭代。
But in all the implementations, the loop waits for 3000 milli-seconds initially and then executes the whole for
loop at once. Is there a way that each iteration is called after waiting for 1000 milli-seconds.
推荐答案
你可以用简单的数学方法解决这个问题。 :
You can work that out with simple math :
for (var i=0;i<=10;i++) {
(function(ind) {
setTimeout(function(){console.log(ind);}, 1000 + (3000 * ind));
})(i);
}
1000ms:0
4000ms:1
7000ms:2
10000ms:3
13000ms:4
...
1000ms : 0
4000ms : 1
7000ms : 2
10000ms : 3
13000ms : 4
...
评论后
您的请求似乎有点模糊。如果你想在最后一次超时后做一些事情,你可以设置一个限制并比较当前的指数:
Following the comments
It seem that your request is a bit blurry. if you want to do something after the last timeout, you can set a limit and compare the current index :
var limit = 10
for (var i=0;i<=limit;i++) {
(function(ind) {
setTimeout(function(){
console.log(ind);
if(ind === limit){
console.log('It was the last one');
}
}, 1000 + (3000 * ind));
})(i);
}
小提琴:http://jsfiddle.net/Tn4A7/
并且只需执行
for (var i=0;i<=10;i++) {
(function(ind) {
setTimeout(function(){console.log(ind);}, 1000 * ind);
})(i);
}
这篇关于JavaScript:用于超时的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!