开发者

How do I delay a jQuery animation until after others finish?

开发者 https://www.devze.com 2022-12-12 22:51 出处:网络
I have a function that does some fairly extensive DOM manipulation, and I want to show a \"Loading...\" spinner while the function runs:

I have a function that does some fairly extensive DOM manipulation, and I want to show a "Loading..." spinner while the function runs:

function showFoos() {
  $('#spinner').show();
  bigHairyDOMManipulation();
  $('#spinner').hide();
}

function bigHairyDOMManipulation() {
  for (var i=0; i < arrayOfFoos.length; i++){
    buildFooBox(arrayOfFoos[i], i);
  }
}

function buildFooBox(foo, index) {
  $('#foos').append(
              $('<li />').append(...)
                         .append(...)
                         ...
             );
}

Unfortunately, all of the append() calls return quickly, so even though the view isn't ready, the function is done and the spinner hides.

I can't think of a good way of chaining all of those appends together into one chain, so I can't just tack the show() on the front and the hide() on the end.

Is there another way to force the hide() ca开发者_开发技巧ll to wait for all the other manipulation to occur?


Having tons of appends and dom manipulation is a very bad idea. It will cause the browser to redraw multiple times in a row which is what slows things down. It looks like you are creating a whole bunch of new elements.

Read 43,439 reasons to use append() correctly to help you understand how to do what you need to with out going crazy with the appends


You could append a script as the last action. Ugly, but from the description of the problem, firing an event won't work.


Wrap the 'bigHairyDOMManipulation' and 'hide' calls on a callback for the show animation.

 function showFoos() {
    $('#spinner').show(function(){
       bigHairyDOMManipulation();
       $('#spinner').hide();
    });
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消