这里是对# Timed array processing in JavaScript这篇文章中的示例做了验证,具体内容我就不重复了,直接看原文。
function chunk(array, process, context){
var items = array.concat(); //clone the array
setTimeout(function(){
var item = items.shift();
process.call(context, item);
if (items.length > 0){
setTimeout(arguments.callee, 100);
} else {
console.timeEnd('test')
}
}, 100);
}
array = new Array(500).fill(Math.floor(Math.random()*100))
process = (v) => {console.log('the ', v)}
console.time('test')
chunk(array, process, window)
运行结果
优化后
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); // 这里的 delay 取的是 25ms
} else {
callback(items);
console.timeEnd('test2')
}
}, 25); // 这里的 delay 取的是 25ms
}
console.time('test2')
timedChunk(array, process, window, () => console.log('end'))
运行结果
同样是处理大小为500的数组,优化后的用时只占优化前的0.06%。