Define timeouts between steps of jQuery.each() loop

10,660

Solution 1

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

Solution 2

Depending on your situation, something like this could work:

$('.some-results').each(function(i) {
  $(this).delay(500 * i).someAction();
});

In this example, you use the index number (i) of the array to have each iteration delayed by 500ms more than the last. Hope this helps.

NOTE: In case it is not clear, someAction() can be whatever you were planning to do with the element. Could be an animation, obtaining a value, etc.

Solution 3

Try this Code:

HTML

<div class="result"></div>
<div class="result"></div>
<div class="result"></div>

Javascript

$('.result').each(function(i) {
  setTimeout(function(){ alert(i);},5000*i);
});

Working JSFiddle

Share:
10,660
István Pálinkás
Author by

István Pálinkás

( [] &lt; {} ) // true ( + "." != + "." ) // true  

Updated on June 27, 2022

Comments

  • István Pálinkás
    István Pálinkás about 2 years

    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.

  • István Pálinkás
    István Pálinkás about 10 years
    As far as I see, this doesn't use any callbacks, it simply sets timeouts IN the steps, not BETWEEN them.