3

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
  • 2,217
  • 7
  • 25
  • 50

3 Answers3

7

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

Adam
  • 6,539
  • 3
  • 39
  • 65
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.

MitulP91
  • 1,279
  • 2
  • 12
  • 24
1

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

Hitesh Modha
  • 2,740
  • 5
  • 28
  • 47