当前位置: 代码迷 >> Web前端 >> 数组任务分解防止页面诈死
  详细解决方案

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

热度:90   发布时间:2012-11-01 11:11:31.0
数组任务分解防止页面假死
当对一个数组的每一项进行处理,处理时间比较长的时候,浏览器会因为忙于计算而无法接收用户的请求,如页面点击无反应等,从而出现假死状态。解决方法:
使用定时器分解任务,在任务切换‘空隙’可以允许浏览器对用户操作进行相应。
原始代码:
for (var i=0, len=items.length; i < len; i++){
    process(items[i]);
}


改进后:
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
  相关解决方案