Define timeouts between steps of jQuery.each() loop

István Pálinkás picture István Pálinkás · May 22, 2014 · Viewed 10.6k times · Source

As far as I know, $.each() is a synchronous function, so I think, somehow it has to be possible - with some sort of technique - to delay the steps of the looping through the array.

I didn't find a proper way yet. How could I set timeouts for it's steps properly?

UPDATE:

The problem, why I need this, is that the number of the steps in the loop, and the calculations are huge, and they make the asynchronous functions too slow. I would like to save some processor speed for them, with defining "priorities" with this delaying. I am using a non-callback function, mostly jQuery.css() in the steps of the loop.

IMPORTANT:

I am looking for a technique to set the delays IN BETWEEN steps, to reduce the amount of calculations, not setting HUGE amounts of timeouts with the loop, what will run by time.

Answer

Adam picture Adam · May 22, 2014

I'd suggest not using .each() but looping the collection manually.:

HTML

<div class="foo">A</div>
<div class="foo">B</div>
<div class="foo">C</div>
<div class="foo">D</div>
<div class="foo">E</div>

Javascript

var collection = $('.foo');
if( collection.length > 0 ){
    var i = 0;
    var fn = function(){
        var element = $(collection[i]);
        console.log(i + ' (' + element.text() + ') : %o', element);
        // Do whatever
        if( ++i < collection.length ){
            setTimeout(fn, 5000);
        }
    };
    fn();
}

Could be fairly easily wrapped into a $('.foo').delayedEach(5000, function(){}) extension if you wanted.

Working fiddle