Matthew Dolman
Matthew Dolman

Reputation: 1800

Wait for a jQueryanimation to complete within for loop

I have something like the following code

for(i=0, j=10; i<j ; i++){
    $('#an-element-'+i).fadeIn();
}

How do I make it so that each iteration in the loop will only start once the fadeIn(); animation has completed?

edit---sorry my bad I had not included the 'i' in the loop

Upvotes: 5

Views: 1491

Answers (5)

gilly3
gilly3

Reputation: 91467

for loops are synchronous, but animations are asynchronous. You'll need to use recursion.

var i = 0, j = 10;
(function fadeNext () {
    if (i < j) {
        $('#an-element-' + i++).fadeIn(fadeNext);
    }
}) ();

http://jsfiddle.net/uq9mH/

Upvotes: 7

wargodz009
wargodz009

Reputation: 305

if you have a fixed delay for all the item you may use this line of code:

 $(this).fadeIn().delay(2000).fadeOut();

instead of

  $(this).fadeIn();

Upvotes: 0

HashimR
HashimR

Reputation: 3833

Try this:

for (i = 0, j = 10; i < j; i++) {
    $('.try').each(function() {
        $(this).delay(1000).fadeOut().delay(1000).fadeIn();
    });
}

You can change the time duration inside the delay function. Here is the jsFiddle.

Upvotes: 0

Jonas H&#248;gh
Jonas H&#248;gh

Reputation: 10874

You can execute code after an animation by placing it in a function passed as the callback parameter:

$("#foo").fadeIn("slow",function () {
  alert("done");
});

But it is not quite clear what you're trying to do. Are you fading the same element 10 times?

Upvotes: 0

JohnP
JohnP

Reputation: 50009

According to your code, your loop will just fade in the same element 10 times.

In any case, what you need is to put the call in the callback of the fadein method : http://api.jquery.com/fadeIn/

Something like this should work (not tested)

var counter = 10;
function fadeIn(elem) {
   $(elem).fadeIn('slow', function(){
       if (counter > 0) {
          fadeIn(elem); //up to you how you figure out which element to fade in
       }
   });
   counter--;
}

//var elem = $('.something');
fadeIn(elem);

Upvotes: 0

Related Questions