zoukankan      html  css  js  c++  java
  • 使用定时器处理数组

    简单的例子:

    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 }
  • 相关阅读:
    Mac上如何用命令行修改proxy设置
    Mac上解决访问github慢问题
    Bootstrap布局
    ListView详解
    sql server命名规范
    表的管理与操作
    常用编程技巧和方法
    有联系的jQuery选择器
    sql基础查询语句
    数值特征
  • 原文地址:https://www.cnblogs.com/qzsonline/p/2567475.html
Copyright © 2011-2022 走看看