I currently have a Javascript forEach() loop, but I need change my code to add a "sleep" every 500th iteration.
This pattern lets me sleep for 3 seconds every iteration:
How do I add a delay in a JavaScript loop?
for (let i=1; i<10; i++) {
setTimeout( function timer(){
alert("hello world");
}, i*3000 );
}
How can I sleep for every 2nd - or every 500th - iteration?
PS:
The solution needs to run on Chrome and IE11.
A recursive timeout solution:
const processInBatches = (array, limit, processFn, timeout) => {
const batch = array.slice(0, limit);
if(!batch.length) {
return;
}
batch.forEach(processFn);
const rest = array.slice(limit);
setTimeout(() => processInBatches(rest, limit, processFn, timeout), timeout);
}
const array = ['a', 'b', 'c', 'd'];
processInBatches(array, 2, (x) => console.log('processing',x), 1000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With