Par*_*gil 16 javascript settimeout
我希望我的for循环不应该立即执行,而是在每次迭代后等待超时.例如:
for(var i=0; i<10; i++) {
console.log(i);
//wait for 1000
}
Run Code Online (Sandbox Code Playgroud)
我在堆栈溢出中发现了许多像这样的解决方案:
for (var i=0;i<=10;i++) {
(function(ind) {
setTimeout(function(){console.log(ind);}, 3000);
})(i);
}
Run Code Online (Sandbox Code Playgroud)
但是在所有实现中,循环最初等待3000毫秒,然后立即执行整个for循环.有没有办法在等待1000毫秒后调用每个迭代.
Kar*_*non 31
你可以用简单的数学方法解决这个问题:
for (var i=0;i<=10;i++) {
(function(ind) {
setTimeout(function(){console.log(ind);}, 1000 + (3000 * ind));
})(i);
}
Run Code Online (Sandbox Code Playgroud)
1000ms:0
4000ms:1
7000ms:2
10000ms:3
13000ms:4
...
看来您的请求有点模糊.如果您想在上次超时后执行某些操作,可以设置限制并比较当前索引:
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);
}
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/Tn4A7/
而这只是做
for (var i=0;i<=10;i++) {
(function(ind) {
setTimeout(function(){console.log(ind);}, 1000 * ind);
})(i);
}
Run Code Online (Sandbox Code Playgroud)
Rok*_*jan 16
不要在循环中创建函数,而是:
(function fiveSeconds (n) {
if (n < 5) setTimeout(function () {
fiveSeconds ( n ); // Redo if n < 5 (and pass n)
}, 1000);
console.log( n++ );
} (0)); // Initialize. n is 0Run Code Online (Sandbox Code Playgroud)
以上将记录10个数字,从0到5,间隔为1秒.
(function fiveSeconds (n) {
console.log( n++ );
if (n <= 5) setTimeout( fiveSeconds, 1000, n ); // Redo if n <= 5 (and pass n)
} (0)); // Initialize. n is 0Run Code Online (Sandbox Code Playgroud)
为什么不使用这样的东西:
var i = 0
var id = window.setInterval(function(){
if(i >= 10) {
clearInterval(id);
return;
}
console.log(i);
i++;
}, 1000)
Run Code Online (Sandbox Code Playgroud)
这是一个es6解决方案。我真的不喜欢将 包装setTimeout在函数中,当您可以简单地使用块作用域变量时,如下所示:
for (let i=0; i<=10; i++) {
setTimeout(() => {console.log(i);}, 1000 * i);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39976 次 |
| 最近记录: |