开发者

Calling multiple functions sequentially with jquery

开发者 https://www.devze.com 2023-01-01 19:59 出处:网络
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 fo

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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消