nabeelfarid
nabeelfarid

Reputation: 4224

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?

Upvotes: 3

Views: 3729

Answers (3)

user113716
user113716

Reputation: 322612

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.

Upvotes: 2

Andy Gaskell
Andy Gaskell

Reputation: 31761

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

Upvotes: 0

reko_t
reko_t

Reputation: 56460

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

Upvotes: 2

Related Questions