使用定时器处理数组

mac2022-06-30  21

简单的例子:

1 for (var i = 0, len = item.length; i < len; i++) { 2 process(item[i]); 3 }

 

优化条件:

1、处理过程是否必须同步? 2、数据是否必须按顺序处理? 都是否,就看下面的代码:

1 function processArray(items, process, callback) { 2 var todo = items.concat(); 3 4 setTimeout(function() { 5 process(todo.shift()); 6 7 if (todo.length > 0) { 8 setTimeout(arguments.callee, 25); 9 } else { 10 callback(items); 11 } 12 }, 25); 13 } 14 15 //使用方法 16 var items = [123, 789, 323, 778, 232, 654, 219, 543, 321, 160]; 17 18 function outputValue(value) { 19 console.log(value); 20 } 21 22 processArray(items, outputValue, function() { 23 console.log("Done!"); 24 });

 

 优化了加载时间的processArray():

1 function timedProcessArray(items, process, callback) { 2 var todo = items.concat(); //克隆原始数组 3 setTimeout(function() { 4 var start = +new Date(); 5 6 do { 7 process(todo.shift()); 8 } while (todo.length > 0 && (+new Date() - start < 50)); 9 10 if (todo.length > 0) { 11 setTimeout(arguments.callee, 25); 12 } else { 13 callback(items); 14 } 15 }, 25); 16 }

 

转载于:https://www.cnblogs.com/qzsonline/archive/2012/06/28/2567475.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)