jqueryjquery-2.0

queue a number of effects synchronously with jquery


Is there are more readable way to queue a number of asynchronous effects that they are executed synchronously?

var element1 = $('#div1');
var element2 = $('#div2');

$(element2).hide();
$(element1).on('click',function(){   
    $(element1).fadeOut(1000,function(){
        $(element2).fadeIn(1000, function(){
            $(element2).hide();
            alert('hello');
        });
    });
}); 

Solution

  • You can prevent the ever-deeper nesting effect if you use a promise-based system.

    $.when(
        $(element1).fadeOut(1000)
    ).then(function () {
        return $(element2).fadeIn(1000);
    }).then(function () {
        return $(element2).hide();
    }).then(function () {
        return $(element1).fadeIn(1000);
    }).then(function () {
        return $(element1).fadeOut(1000);
    });
    

    Demo: http://jsfiddle.net/tYhNq/1

    You'll notice this makes it very easy to change the order of the animations.

    The "trick" is that the $.when() method returns the promise object associated with the first animation, so then you can just chain a bunch of .then() calls, noting that each then() callback should return the result of its animation.

    Of course you can directly chain animations on the same element, e.g. .fadeIn(100).fadeOut(100)...