Why is it ok to connect jquery effects instead of using callbacks

The jquery documentation states that if you want to add a class after applying the effect to highlight, you must use a callback:

// Fade in all hidden paragraphs; then add a style class to them (not quite right)
$( "p.hidden" ).fadeIn( 750 ).addClass( "lookAtMe" );

// Fade in all hidden paragraphs; then add a style class to them (correct with animation callback)
$( "p.hidden" ).fadeIn( 750, function() {
// this = DOM element which has just finished being animated
$( this ).addClass( "lookAtMe" );
});

      

However, you can chain two effects without using a callback:

$(".something").fadeOut().fadeIn();

      

Why? you don't need to use a callback either:

$( ".something" ).fadeOut( 750, function() {
   $( this ).fadeIn();
});

      

+3


source to share


3 answers


From my point of view, when you do an operation like fadeIn / fadeOut, what you do is create a request that is put into an internal animation queue that performs the actions in FIFO mode. Others may describe it in detail, but since it works, it doesn't require the use of callbacks.



+5


source


Callbacks make sense for asynchronous operations. So the callback is if you want something to happen after the fade is complete. In your case, the subsequent chain .addClass()

does not wait for the fade to complete. This happens immediately.



+1


source


Because, simply put, the challenge is .fadeIn

not waiting. All it does is add the effect to the queue and then continue with whatever other code you have. What the jQuery documentation says is that if you want to add a class to an element after the effect has finished (which they just use as an example), you have to use a callback that is called at the end of the effect.

Also, you can absolutely chain the two effects using callbacks, but these are unnecessary amounts of input (and developers tend to be as lazy as possible). The reason it works to bind two effects together without a callback is because it calls .fadeIn

or .fadeOut

adds the appropriate effect to the jQuery effect queue for that DOM element. Effects play from a queue in turn, in sequence, so no matter how quickly you add them to the queue, they will always play at the correct speed and timing.

+1


source







All Articles