views:

39

answers:

1

Hi folks,

I have a javascript function that calls itself on callback, and I'm wondering how to chain other functions after all callbacks are finished? Perhaps best explained by code:

$(document).ready(function() {
    sequentialFadeIn($('#demolist li'));
});

function sequentialFadeIn(item) {
    item.eq(0).fadeIn("fast", function() {
        (item=item.slice(1)).length && sequentialFadeIn(item)
    }
}

So, the sequentialFadeIn function iterates through all list elements in 'demolist' and fades them in one after the other. What I'd like to do is perform another function (let's call it "sequentialMoveUp") after all iterations of sequentialFadeIn have been run. I'm moderately new to jQuery, so this question may well be something like 'how to chain non-jQuery methods in jQuery' or 'how to run callbacks on non-jquery methods in jQuery'...or then again it may not. Any ideas most appreciated.

+1  A: 

You need a last callback passed to sequentialFadeIn. The next thing is to add an extra case in your conditional logic for when there's no item left. Then you call the last callback. [Demo]

Code

function sequentialFadeIn(items, callback) {
    items.eq(0).fadeIn("fast", function() {
       items = items.slice(1);
       if (items.length) // items left
         sequentialFadeIn(items, callback);
       else              // no items left -> finished
         callback();
    });
}

Usage

sequentialFadeIn($('#demolist li'), sequentialMoveUp);
galambalazs
Perfect - exactly what I was after. Many thanks. ;-)
unclaimedbaggage