【发布时间】:2017-10-30 12:29:08
【问题描述】:
我想保持for-loop 的迭代,直到前一个迭代中的功能完成。我见过很多关于setTimeout 的问题,但没有一个能满足我的要求。谁能帮帮我?
function abcd() {
var exArray = [0, 0, 1, 1, 1, 0, 0, 0];
var index = 0;
for (var i = 0; i < exArray.length; i++) {
if (exArray[i] == 1) {
addDelay(++index);
} else {
console.log('ended at ' + i);
}
}
}
seTimeout 功能是这样的
function addDelay(index) {
setTimeout(function() {
console.log("in Timeout loop:" + index);
}, 2000 * index);
}
预期的输出是
结束于 0
结束于 1
在超时循环中:{{index}} // 等待延迟
在超时循环中:{{index}} // 等待延迟
在超时循环中:{{index}} // 等待延迟
5点结束
6点结束
7点结束
但我在控制台中看到的输出是:
结束于 0
结束于 1
5点结束
6点结束
7点结束
在超时循环中:{{index}} // 等待延迟
在超时循环中:{{index}} // 等待延迟
在超时循环中:{{index}} // 等待延迟
我希望ended at 5 等到第 3、第 4、第 5 个数组索引的超时功能。我需要有人帮我解决这个问题。提前致谢。
【问题讨论】:
-
你的
setTimeout代码部分写得很好...尝试 ES6 方法:setTimeout(() => { console.log('waiting 1 second...'); }, 1000); -
setTimeout将安排一个后台任务,然后立即返回。所以你的循环继续运行,延迟后超时功能被执行,所以它不能那样工作。在您的情况下,最好的解决方案可能是摆脱 for 循环并用回调循环替换它,因此在每次延迟执行后,它会使用下一个索引调用“循环”,直到数组结束。
标签: javascript for-loop settimeout