javascript - 如何使用 underscore.js 进行屈服循环?

标签 javascript underscore.js settimeout

所以,我想循环遍历数百个项目,并且在处理每个项目时不阻塞 UI 线程——总共可能需要几秒钟的工作,所以我想经常让步。有几本书推荐了如下所示的循环:

function processArray(items, process, callback){
    var todo = items.concat(); //create a clone of the original
    setTimeout(function () {
        process(todo.shift());
        if (todo.length > 0) {
            setTimeout(arguments.callee, 100);
        } else {
            callback(items);
        }
    }, 100);
}

(引用http://answers.oreilly.com/topic/1506-yielding-with-javascript-timers/)

上次我使用了一个聪明的循环,我发现 underscore 已经支持它并且可能有更好、更稳定等的版本。如何在下划线中执行上述操作? _.each 似乎不适用,_.each 似乎没有产生或提供更改暂停时间的选项。

最佳答案

查看异步库
https://github.com/caolan/async
并使 process 成为接受回调的异步函数。

function process(item, cb){
    //replace this code block with your actual process logic
    setTimeout(function () {console.log(item); async.nextTick(cb);}, 500);
}
function processArray(items, iterator, callback){
    var todo = items.concat(); //create a clone of the original
    async.eachLimit(todo, 4, iterator, function(){ 
        //replace 4 with the desired number of simultaneous asynchronous operations
        //if `process` isn't too computationally expensive, you could try 50 
        callback(); //all done
    });
}

processArray([0,1,2,3,4,5,6,7,8,9,10], process, function(){
    console.log('all done');
});

演示:http://jsbin.com/izumob/1/

关于javascript - 如何使用 underscore.js 进行屈服循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17215578/

相关文章:

javascript - For 循环中的 setTimeout 不起作用

javascript - 纯 WebGL 虚线

javascript - 为什么 JavaScrips 仅在加载页面后才起作用?

javascript - 使用 Underscorejs 从 json 中提取值

html - 使用 CSS 网格将 HTML 表格与模板绑定(bind)

javascript - JQuery 在 5,10,15...55 整点后每 5 分钟运行一次

javascript - 在两个 Canvas 之间复制会导致模糊

php - 通过 javascript 重定向 html 传递 php 变量?

javascript - 如何使用 Underscore 在 JavaScript 数组中获取重复项

javascript - 在 React Hooks 中使用 SetTImeout 的交通灯