Wait for a jQueryanimation to complete within for

2020-06-19 17:36发布

问题:

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

回答1:

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/



回答2:

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);


回答3:

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?



回答4:

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.



回答5:

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();