Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery chaining vs. callbacks for animation functions

Say I have some element I want to animate:

$('.hey').show(1000).slideUp(1000);

What's the difference between this and:

$('.hey').show(1000, function() {
  $(this).slideUp(1000);
});

in terms of what happens internally? As far as I know, animations are asynchronous in jQuery. So the first example, show and slideUp should fire at the same time. In the second, slideUp should fire only after show ends.

Yet, for some reason, people like on this answer say they're the "same". Why are they same despite the (obvious) fact they work different (in the first example, the return will happen immediately, unlike with the second one)?

like image 231
daremkd Avatar asked Jan 27 '16 12:01

daremkd


1 Answers

Yet, for some reason, people like on this answer say they're the "same".

You're right, they aren't. There's a particularly large difference between them if more than one element matches .hey. But with your quoted code, although the sequence of steps they take is different, they end up doing much the same thing.

Why are they same despite the (obvious) fact they work different (in the first example, the return will happen immediately, unlike with the second one)?

In both of those examples, the code runs and completes ("returns") immediately.

In the first example, the call to slideUp happens immediately but jQuery handles that call by adding the slideUp animation to the end of the animation queue and returning; the actual slideUp happens later, when reached in the animation queue.

In the second example, the call to show happens immediately and then, later when the animation is complete, the call to slideUp is done.

The key difference when multiple elements match your selector is that in your first example, there is one call to slideUp, which adds the slideUp operation to the animation queue for the current set of elements in the jQuery object you called it on. In the second, there are multiple calls to the completion callback, one for each element as it completes.

Another very important difference was highlighted by Arun P Johny in the comments: If you were to add another animation function to those same elements later, with the first example it would be added to the queue after the slideUp, but in the second example the slideUp would be after that other animation.

But with your quoted code, again, while they take different roads to get there, they end up doing much the same thing.

like image 70
T.J. Crowder Avatar answered Sep 28 '22 12:09

T.J. Crowder