-2

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

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,所以如果库中有任何东西可以帮助完成这项任务,我会使用它。一切都发生在浏览器中。

4

1 回答 1

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();
        });
    }
})();
于 2013-06-19T07:09:36.070 回答