您的主循环正在连续执行setTimeout 函数。由于此函数的 async 特性,您将期望看到函数在它们之间没有延迟地执行。
如果你想要近似的效果,你可以使用setInterval,当函数的执行时间远小于延迟时间。这将与亚当的回答相同。
但对于确切的“在每个循环之间创建延迟”,您将需要一些回调。
首先要记住:
function main() {
doWork(items, 0, items.length);
}
function doWork(items, i, loopLength) {
// The bit in the loop
console.log(i + ". " + items[i]['name']);
priceManagement.FindPrices(items[i]['name']);
i++;
if (i < loopLength) {
delayDoWork(items, i, loopLength);
}
else {
// Do rest in the main
...
}
}
function delayDoWork(items, i, loopLength) {
setTimeout(function(items, i, loopLength)
{
doWork(items, i, loopLength);
}, 3000, items, i, loopLength);
}
这将保证循环之间的精确延迟。
编辑
您可能想为此做更多的实验,因为我不是专家,知道setInterval 是如何设计为在 JS 中工作的,因为它本质上不是多线程?起点将考虑来自此SO的以下引用
实际上,setTimeout() 在执行队列的末尾重新排队新的 JavaScript。