How do you chain functions dynamically in jQuery?

Posted by clarke78 on Stack Overflow See other posts from Stack Overflow or by clarke78
Published on 2010-06-02T22:40:21Z Indexed on 2010/06/02 22:44 UTC
Read the original article Hit count: 167

Filed under:
|
|
|
|

I want to loop through an object that contains functions which will execute one after another. My most ideal approach would be to have these chain somehow (ie. func2 waits for func1 and func3 waits for func2) but this needs to happen dynamically and the functions will all have different durations.

I'm using jQuery so I thought that perhaps "queue()" may help but I haven't worked with it much.

A main concern is to not add any scope/callbacks to the functions within the object. I'd rather somehow enclose them within a parent function to execute within the loop in order to create the callback/chaining.

Here's an example of what I've got now, but dumbed down. Thanks for any help!

var obj = [
{'name':'func1','callback':function(){ alert(1); }},
{'name':'func2','callback':function(){ alert(2); }},
{'name':'func3','callback':function(){ alert(3); }}
];

$.each(obj, function(x, el) { 
    el.callback();
});

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery