Your main loop is executing setTimeout
functions continuously. Due to the async nature of this function, you will expect to see the function being executed without delay between them.
You can use setInterval
if you want approximate effect, when the executing time of the function is much less than the delay time. This will achieve the same with Adam's anwer.
But for the exact "create a delay between every loop", you will need some call backs.
First come in mind:
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);
}
This will guarantee the exact delay between loops.
EDIT
You may want to do more experiment for this, as I'm not an expert knowing how setInterval
is designed to work in JS, as it's not multi threading in nature? Start point will be considering the quote below from this SO
In actuality, setTimeout() re-queues the new JavaScript at the end of the execution queue.