最近项目有个功能需要通过JS处理一个比较大的数组,不超过一千(也不是很大-.-),不过用传统的循环处理这已足以让你的浏览器卡上一小会儿了。
刚好从一文章间接找到N久前看过的另一篇关于大数组优化的文章 Timed array processing in JavaScript,当时没这需要所以没去细看,这次记录一下。
下面是文章里总结出来的一段通用的核心函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function timedChunk(items, process, context, callback){ var todo = items.concat(); //create a clone of the original setTimeout(function(){ var start = +new Date(); do { process.call(context, todo.shift()); } while (todo.length > 0 && (+new Date() - start < 50)); if (todo.length > 0){ setTimeout(arguments.callee, 25); } else { callback(items); } }, 25); } |
