从JavaScript数组执行多个回调

时间:2013-06-19 06:04:01

标签: javascript jquery

我有一个回调数组,因此每个回调都会在作业完成时执行另一个回调。例如:

var queue = [
    function (done) {
        console.log('Executing first job');
        setTimeout(done, 1000); // actually an AJAX call here
            // I can't call abort() for the request
    },
    function (done) {
        console.log('Executing second job');
        setTimeout(done, 1000);
            // also AJAX call here
            // it is made from a third-party library that I can't change
            // this means that I can't call abort() on it
    },
    function (done) {
        console.log('Executing third job');
        setTimeout(done, 1000);
    },
    function (done) {
        console.log('Executing fourth job');
        setTimeout(done, 1000);
    } // and so forth
];

var proceed = true;

(function dequeue() {
    var fn = queue.shift();
    proceed && fn instanceof Function && fn(dequeue);
})();

对我来说很好,除了为了加快一切,我最好一次启动四个回调,同时仍然可以通过从其他地方更改proceed标志来停止进一步执行。我该怎么做?

我在这个项目中使用了最新版本的jQuery,所以如果库中有任何东西可以帮助完成这个任务,我会使用它。一切都在浏览器中发生。

1 个答案:

答案 0 :(得分:1)

http://jsfiddle.net/2Jg6r/

var queue = [];
// let's think we have a thousand of jobs
for (var i = 0; i < 1000; i++) {
    (function(jobNumber) {
        queue.push(function (done) {
            console.log('Started job '+ jobNumber);
            setTimeout(function() {
                console.log('Finished job '+ jobNumber);    
                done();
            }, 1000);
        });
    })(i);
}

var proceed = true;

setTimeout(function() {
    console.log('Full stop called after 10 seconds');
    proceed = false;
}, 10000);

queue.depth = 0;
queue.maxDepth = 4;

(function dequeue() {
    while (queue.depth < queue.maxDepth) {
        queue.depth += 1;
        var fn = queue.shift();
        proceed && fn instanceof Function && fn(function() {
            queue.depth -= 1;
            dequeue();
        });
    }
})();