Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery while loop not waiting for animation

I have a jQuery function that does a .clone() on an object, and then an .insertAfter() and a .slideDown() on the cloned object. This whole function is wrapped inside a while loop. I will keep this as short and concise as possible and show a generic example:

while (statement) {
    // code for clone and insert  ...
    $("#newly_created_object").slideDown(500);
}

How can I prevent the next while-loop from firing before the .slideDown() animation (or any other kind of animation for that matter) ends ?

Thank you in advance !

like image 709
Valentin Flachsel Avatar asked Apr 12 '26 03:04

Valentin Flachsel


2 Answers

You might want to create and insert all of the elements first, storing them in an array. Then you can use a recursive function to pop one element off the array and animate it, calling your function on the remaining elements in the callback handler for the animation -- to ensure that the first is complete before the next starts.

    ...
    var elems = [];
    while (statement) {
        var elem = ...clone and insert element, returning element...
        elems.push(elem);
    }

    animateElems( elems);
}


function animateElems( elems )
{
    if (elems.length > 0) {
        var elem = elems.shift();
        $(elem).slideDown( 500, function() {
             animateElems( elems );
        }
    }
}
like image 63
tvanfosson Avatar answered Apr 14 '26 17:04

tvanfosson


You have to make the animation synchronous, but that is not a good idea, as it will block the browser and annoy the user. Here is another question on that topic: JQuery synchronous animation

A better idea is to use the callback function, which will be executed when the animation is done. Like so:

function cloneAndInsert(elm){
  if(statement){
    // code for clone and insert
    $("#newly_created_object").slideDown(500, function(){
      cloneAndInsert(elm);
    });
  }
}

This code will call itself when it is done with one object (recursively).

like image 40
Marius Avatar answered Apr 14 '26 17:04

Marius