解决方案之一是下面的timeChunk函数,timeChunk 函数让创建节点的工作分批进行,比如把1秒钟创建1000个节点,改为每隔200毫秒创建8个节点。
timeChunk函数接受3个参数,第1个参数是创建节点时需要用到的数据,第2个参数是封装了创建节点逻辑的函数,第3个参数表示每一批创建的节点数量。代码如下:
var timeChunk = function(array,func,count){
var timer;
var start = function(){
for(let i=0,len=Math.min(count||1,array.length);i<len;i++){
func(array.shift());
}
}
return function(){
timer=setInterval(()=>{
if(!array.length&&timer)return clearInterval(timer);
start();
},200);
}
}
let ary = [];
for(let i=0; i<100000; i++){
ary.push(i);
}
const renderHtml = timeChunk(ary,function(res){
const div = document.createElement("div");
div.innerHTML = res;
document.body.appendChild(div);
},8);
renderHtml();