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.

2
  • Can you describe exactly what you're trying to do. This question is the definition of an XY problem. Commented May 22, 2014 at 7:11
  • like jsfiddle.net/arunpjohny/mu6JB/1 ? Commented May 22, 2014 at 7:18

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

As far as I see, this doesn't use any callbacks, it simply sets timeouts IN the steps, not BETWEEN them.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.