forTime循环中的setTimeout一次触发 [英] setTimeout in for loop fires all at once
本文介绍了forTime循环中的setTimeout一次触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在for循环中运行setTimeout.我遵循了将setTimeout移到单独函数中的建议.但是,似乎一切都在循环结束时立即触发.
I'm trying to run a setTimeout inside a for loop. I've followed recommendations to move the setTimeout into a separate function. However, everything seems to fire at once, at the end of the loop.
在此示例中,我希望console.logs每秒触发一次.
In this example, I'd like the console.logs to fire every second.
function setDelay(i) {
setTimeout(function(){
console.log(i);
}, 1000);
}
for (var i = 1; i <= 10; ++i) {
setDelay(i);
}
推荐答案
最简单的方法是将超时乘以索引:
The easiest way to achieve this is to multiply timeout by index:
function setDelay(i) {
setTimeout(function(){
console.log(i);
}, i * 1000);
}
这篇关于forTime循环中的setTimeout一次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文