开发者

Making jQuery Fadeout() callback function synchronous

I am trying to do something like this

01 ...do some heavy duty stuff

02   //delete some rows <tr>
03 $('...').fadeOut(function () {
04     $(this).remove();
05 }); 

06 ...do some heavy 开发者_运维知识库duty stuff
07 ...add some rows <tr>

However the fadeOut's call back function doesn't get fire immediately. Because of this my logic of adding new rows after removing them does not work properly. I know I can place the code at line 6 and 7 inside the callback but I don't want to do this because the callback has alot of logic and gets called from other places.

Is there a way I can force fadeout() to complete executing its callback before it reaches line 6?


No, and even if there was a way, it'd be a bad idea as it'd block many browser from updating its GUI completely, making it hang.

If you have a common callback in the fadeOut function that is used in many places (let's call this commonCallback), all you need to do is wrap it inside another function:

// ...do some heavy duty stuff

//delete some rows <tr>
$('...').fadeOut(function () {
    commonCallback();

    // ...do some heavy duty stuff
    // ...add some rows <tr>
}); 


One safe option would be to use a setTimeout() with the duration set to the same as the fadeOut().

$('...').fadeOut(function () {
     $(this).remove();
}, 600); 

setTimeout(function() {
    // place your code that should wait
    //   for the fadeOut to complete
    //   inside here
}, 600);

Note that the duration for both are set to the same 600ms duration.

Any code you plase inside the setTimeout function will wait 600ms to execute without freezing the browser.


Maybe you could set a flag? I don't think that's a good option but it may work.

What might be more important is the structure of your code. Not everything needs to be anonymous. Even if the callback is complex you can still organize your code so that moving lines 6 and 7 into the callback is easy. For example:

$('...').fadeOut(function() {
   doRemoveAndLotsOfCoolStuff();
   doLines6and7();
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜