当对一个数组的每一项进行处理,处理时间比较长的时候,浏览器会因为忙于计算而无法接收用户的请求,如页面点击无反应等,从而出现假死状态。解决方法:
使用定时器分解任务,在任务切换‘空隙’可以允许浏览器对用户操作进行相应。
[b]原始代码:[/b]
[b]改进后:[/b]
将其封装为一个函数,以便重用:
例子
原文出自:High Performance Javascript
使用定时器分解任务,在任务切换‘空隙’可以允许浏览器对用户操作进行相应。
[b]原始代码:[/b]
for (var i=0, len=items.length; i < len; i++){
process(items[i]);
}
[b]改进后:[/b]
var todo = items.concat(); //create a clone of the original
setTimeout(function(){
//get next item in the array and process it
process(todo.shift());
//if there's more items to process, create another timer
if(todo.length > 0){
setTimeout(arguments.callee, 25);
} else {
callback(items);
}
}, 25);
将其封装为一个函数,以便重用:
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, 25);
}
else {
callback(items);
}
}, 25);
}
例子
var items = [123, 789, 323, 778, 232, 654, 219, 543, 321, 160];
function outputValue(value){
console.log(value);
}
processArray(items, outputValue, function(){
console.log("Done!");
});
原文出自:High Performance Javascript