jQuery: using Deferred objects to chain animations

jQuery: using Deferred objects to chain animations

jQuery's Deferred objects can be used to chain animations.

jQuery's Deferred objects can also be used to chain animations in a queue. As the API's documentation states, jQuery.Deferred(), introduced in version 1.5, is a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. That's ideal for animation queuing.

In its simplest form, a two-steps chain can be created with a single Deferred object and with the .done() callback which will fire when the first code block has been executed.

Don't forget to invoke the .resolve() method on the Deferred object. If you don't do this, the state of the object won't be set to resolved and the second code block won't be never executed.


$.Deferred(function(def) {
    $('#test-a').animate({
        left: 100
    });
}).done(function(def) {


    $('#test-b').delay(1000).animate({
        top: -116
    });


}).resolve();​

You can also add a delay to the execution of the second routine by using the .delay() method. You can see the demo on this page.