jQuery while loop not waiting for animation

让人想犯罪 __ 提交于 2019-12-24 03:25:47

问题


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 !


回答1:


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



回答2:


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




回答3:


An alternate solution, unless you want to avoid closures, is to use jQuery's queue() and dequeue() functions:

while (statement) {
  var elem = ... clone and insert element, returning element ...

  $(document).queue((function (el) {
    return function () {
      el.slideDown(function () { $(document).dequeue(); });
    }; 
  })(elem));
}

Working demo: http://jsbin.com/axafo (editable via: http://jsbin.com/axafo/edit#javascript)




回答4:


You can check if element is still being animated like that:

while (statement) {
    if ($("#newly_created_object").is(":animated")) continue;
    $("#newly_created_object").slideDown(500);
}

Although it may not be the best solution, because you will keep user browser busy.

The correct way to do actions after animation is finished:

$("#newly_created_object").slideDown(500, function () {
    alert('this alert box appears when animation is finished');
});


来源:https://stackoverflow.com/questions/1898496/jquery-while-loop-not-waiting-for-animation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!