Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 590
Matthew Dolman Avatar asked Nov 24 '11 04:11

Matthew Dolman


1 Answers

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/

like image 126
gilly3 Avatar answered Sep 18 '22 06:09

gilly3