这会产生 2 秒的延迟并运行循环。我需要为每次迭代创建 2 秒的延迟,而不仅仅是一次。
var myArray = ['test1','test2','test3'];
function doSetTimeout(index) {
setTimeout(function() { console.log(myArray[index]) }, 2000);
}
var index;
for (index = 0; index < myArray.length; ++index) {
doSetTimeout(index)
}
预期结果是:
test1
(2 second delay)
test2
(2 second delay)
test3
最佳答案
只需将延迟乘以指数即可
var myArray = ['test1','test2','test3'];
function doSetTimeout(index) {
setTimeout(function() { console.log(myArray[index]) }, index * 2000;
}
var index;
for (index = 0; index < myArray.length; ++index) {
doSetTimeout(index)
}
关于javascript - 如何使用 setTimeout 为每次迭代添加延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552935/