所以,我想循环遍历数百个项目,并且在处理每个项目时不阻塞 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');
});
关于javascript - 如何使用 underscore.js 进行屈服循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17215578/