js优化循环次数过多的问题(使用setTimeout)

直接上代码:

const res = [];
function test1() {
    for(let i = 0; i<50000000; i++) {
    res.push(i)
    }
    if (res.length < 50000000) { // 是否已完成
        setTimeout(test1, 0);
    }
    return res;
}
console.time("耗时")
console.log(test1().length)
console.timeEnd("耗时")      

 

 

 

 
posted @ 2022-11-09 11:08  zaijinyang  阅读(188)  评论(0编辑  收藏  举报