darcy
darcy

Reputation: 465

Calling multiple functions sequentially with jquery

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();
});

Upvotes: 1

Views: 1587

Answers (2)

Jonathan
Jonathan

Reputation: 32868

The async-waterfall library can also help you do this.

Upvotes: 0

Matey Yanakiev
Matey Yanakiev

Reputation: 167

Try this:

var obj = [
     function() { alert(1); },
     function() { alert(2); },
     function() { alert(3); }
];
$.each(obj,function() {
    // Replace 500 with whatever you want
    setTimeout(this,500);
});

You can also use a for loop, since there is no reason to use $.each, although it's no problem:

for (var i = 0; i < obj.length; i++) {
    // Replace 500 with whatever you want
    setTimeout(this[i],500);
}

It also depends on whether you want to have different timing based on what function you're executing.

Here is for a for loop:

for (var i = 0; i < obj.length; i++) {
    // Replace 500 with whatever you want
    setTimeout(this[i],500 * i);
}

And with $.each:

$.each(obj,function(i) {
    // Replace 500 with whatever you want
    setTimeout(this,500 * i);
});

Upvotes: 1

Related Questions