使用定时器来控制一次执行的任务数量

因为JS执行期间,浏览器不会立即出发UI更新,甚至可能新的UI更新任务不会被创建并加入到任务队列。所以应避免长时间执行JS。根据业界的研究,应避免JS允许时间超过100ms。
当允许大量的任务时,可以使用定时器来控制一次执行的任务数量。

function timedProcessArray(items,process,callback){
   var todao=item.concat();
   setTimeout(function(){
      var start= new Date();
      do {
         process(todo.shift());
      }while(todao.length>0 && (new Date()-start<50));
      if (todao.length>0){
          setTimeout(arguments.callee,25); 
      }
      else {
          callback(items);
      }
   },25);
}

猜你喜欢

转载自www.cnblogs.com/lianjinzhe/p/13183739.html