数组任务分解防止页面假死

当对一个数组的每一项进行处理,处理时间比较长的时候,浏览器会因为忙于计算而无法接收用户的请求,如页面点击无反应等,从而出现假死状态。解决方法:
使用定时器分解任务,在任务切换‘空隙’可以允许浏览器对用户操作进行相应。
[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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值