这会产生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
答案 0 :(得分:1)
只需将您的延迟乘以索引
即可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)
}