我有代码要等待函数在启动循环的下一部分之前完成。
我稍微简化了场景(我在正常情况下使用I / O,这里我只是使用setTimeout来尝试了解发生了什么):
var total = 0;
var starttime = Date.now();
for (i = 5; i > 0 ; i--) {
setTimeout(console.log("This should take " + i + " seconds and be displayed after " + total
+" seconds. It took " + (Date.now() - starttime) + "ms"),i*1000);
total += i;
}
var endtime = Date.now();
console.log( endtime - starttime );
我的输出是:
This should take 5 seconds and be displayed after 0 seconds. It took 24ms
This should take 4 seconds and be displayed after 5 seconds. It took 27ms
This should take 3 seconds and be displayed after 9 seconds. It took 29ms
This should take 2 seconds and be displayed after 12 seconds. It took 30ms
This should take 1 seconds and be displayed after 14 seconds. It took 30ms
30
有人可以帮助我理解并更改以使我的代码运行14秒吗?
编辑:这个问题与睡眠问题不同(Stackoverflow建议我解释为什么我的问题不同),因为我使用setTimeout的事实是任意的。我想要知道的是,在我继续下一次迭代之前,循环的前一次迭代已经完成。