Vincent Chan
Vincent Chan

Reputation: 482

When to return a jQuery function as opposed to just calling it?

I've been doing some reading about queueing JS callbacks without stacking them over here, How do I animate in jQuery without stacking callbacks?

I've tried playing around Julian Aubourg's answer, and I noticed that after removing the "return" statements from the functions, everything happens at once.

I'm just wondering what the behavior of these return statements are, and what role they play in making this code synchronous.

    $('div1').fadeOut('slow').promise().pipe(function() {
        return $('div2').fadeOut('slow');
    }).pipe(function() {
        return $('div3').animate({ top: 500 }, 1000 );
    });

Upvotes: 2

Views: 69

Answers (1)

adeneo
adeneo

Reputation: 318302

All jQuery animations now return their own promise, so basically you're returning a promise that is resolved when the animation completes when you do :

return $('div2').fadeOut('slow');

It would be equivalent to

var def = new $.Deferred();
$('div2').fadeOut('slow', function() {
    def.resolve();
});
return def.promise();

Upvotes: 4

Related Questions