paulsm4
paulsm4

Reputation: 121619

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

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.

Upvotes: 3

Views: 816

Answers (2)

Mark
Mark

Reputation: 92440

You could create a function that captures a looping variable in a closure and returns a simple function with a loop that returns on batch sizes. The effect is that it lets you continues the for loop where you left off. If you have it return a boolean indicating whether or not it's done you can wrap the whole thing in a setInterval. Easier to show than explain:

function batch(batch_size, end){
    var i = 0                                  // capture i in closure
    return function(){
        for(i; i <= end; i++){
            console.log("doing something", i)  // work goes here
            if (!((i+1) % batch_size)) return i++
        }
        return false
    }
}
var f = batch(5, 11)                           // 0 - 11 batched in groups of 5
if (f()){                                      // start immediately, then setInterval if not finished in one batch.
    var interval = setInterval(() => {
    f() ||  clearInterval(interval)
    }, 2000 )
}

Upvotes: 1

Andy Ray
Andy Ray

Reputation: 32066

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);

Upvotes: 3

Related Questions