【问题标题】:Execute multiple callbacks from a JavaScript array [closed]从 JavaScript 数组执行多个回调 [关闭]
【发布时间】:2013-06-19 15:09:36
【问题描述】:

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

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

【问题讨论】:

  • JavaScript 是单线程的,因此并行执行它们不会加快任何速度。
  • @Blender,你是对的,除了 AJAX 中的第一个 A 代表异步,这表明我们仍然可以在某种后台线程中完成某些事情
  • @sanmai 即使 ajax 是异步的,在某个时间点只会执行一个 javascript 上下文
  • @ArunPJohny 我很好;查看更新的问题
  • @sanmai:我认为 AJAX 并不意味着 JS 中的多线程。这取决于服务器和浏览器。检查这个问题stackoverflow.com/questions/2914161/ajax-multi-threaded

标签: javascript jquery


【解决方案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();
        });
    }
})();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多