Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sleep every N iterations in a Javascript loop?

Tags:

javascript

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.

like image 242
paulsm4 Avatar asked Mar 25 '26 05:03

paulsm4


1 Answers

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);
like image 188
Andy Ray Avatar answered Mar 27 '26 18:03

Andy Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!