使用定时器处理数组

简单的例子:

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 }

 

posted @ 2012-06-28 13:45  小猩猩君  阅读(837)  评论(0编辑  收藏  举报