views:

283

answers:

2

Chaining is great in jQuery, but it chains the trigger of each event and doesn't wait for the previous event to finish. This is noticeable primarily when animating.

As such, the workaround I've seen is to use call back functions. The only drawback is if, say, you have 4 things that you want to animate in succession.

Admittedly, this is probably something you don't want to do very often, but when you do, the markup seems to get a bit verbose. Example (pseudocode):

element.animate(fast, callBackFunction1(element1,element2,element3);

function callBackFunction1(element1,element2,element3){
    element1.animate(fast, callBackFunction2(element2,element3));
};

function callBackFunction2(element2,element3){
    element2.animate(fast, callBackFunction3(element3));
};

function callBackFunction3(element3){
    element3.animate(fast);
};

In that situation, is that the best/most succinct way to go about things?

+3  A: 

Try the following.. :)

element.animate(fast, function() {
    element1.animate(fast, function() {
        element2.animate(fast, function() {
            element3.animate(fast);
        });
    });
});
PKKid
I like how that logically groups the chain together. Thanks!
DA
+1  A: 
var animElements = [
    element,
    element1,
    element2,
    element3,
];

function animateChain(elements) {
    if(elements.length > 0) {
        var element = elements.pop();
        element.animate("fast", function(){ animateChain(elements); });
    }
}

animateChain(animElements);
joshperry
Being recursive, is that a big no-no? I like the logic of recursion but know that's sometimes seen as a bad thing.
DA
follow the flow carefully, this really isn't recursion. The callback is what is calling back into `animateChain` not `animateChain` itself. It's more of an iterative approach.
joshperry
ah! That is a clever way to write it. Thanks, Josh!
DA