如何创建一个非阻塞循环 JS?
How to create a non blocking loop JS?
我找不到这个问题的解决方案:
如果你想在codepen或其他人身上测试你这边的问题,我给你留一个小例子:
您需要 html 中的输入类型复选框用于测试和 JS 代码:
const array = []
for (let i = 0; i < 10000000; i++) array.push(i)
console.log(array.length)
其实我的问题是,在这段代码的执行过程中,如果我点击输入,它只会在for执行结束时才会被检查。
(客户渲染很不爽)
我知道可以在计算完成后不屏蔽网站,但那又如何呢?
如果你有解决方案,我很感兴趣,甚至是曲目。谢谢!
一种方法是使用某种异步模式来避免事件循环阻塞太久。
例如像这样创建一个异步迭代器:
async function doAsyncNTimes(n, process) {
return new Promise(resolve=>{
function helper(index) {
if (index >= n) {
resolve();
return;
}
process(index);
setTimeout(()=>{
helper(index + 1);
}
)
}
let index = 0;
helper(index);
});
}
array = [];
doAsyncNTimes(10000, (index)=>{
array.push(index);
}
).then((ret)=>{
console.log(array)
});
这样你只会在一次迭代 运行 时阻塞事件循环,然后尽快安排下一次迭代。
如果需要,您甚至可以使 process
异步,如果它的计算量很大,那将是有益的。处理数百万项会花费一些时间,但是 UI 根本不会阻塞。
我找不到这个问题的解决方案:
如果你想在codepen或其他人身上测试你这边的问题,我给你留一个小例子:
您需要 html 中的输入类型复选框用于测试和 JS 代码:
const array = []
for (let i = 0; i < 10000000; i++) array.push(i)
console.log(array.length)
其实我的问题是,在这段代码的执行过程中,如果我点击输入,它只会在for执行结束时才会被检查。
(客户渲染很不爽)
我知道可以在计算完成后不屏蔽网站,但那又如何呢?
如果你有解决方案,我很感兴趣,甚至是曲目。谢谢!
一种方法是使用某种异步模式来避免事件循环阻塞太久。 例如像这样创建一个异步迭代器:
async function doAsyncNTimes(n, process) {
return new Promise(resolve=>{
function helper(index) {
if (index >= n) {
resolve();
return;
}
process(index);
setTimeout(()=>{
helper(index + 1);
}
)
}
let index = 0;
helper(index);
});
}
array = [];
doAsyncNTimes(10000, (index)=>{
array.push(index);
}
).then((ret)=>{
console.log(array)
});
这样你只会在一次迭代 运行 时阻塞事件循环,然后尽快安排下一次迭代。
如果需要,您甚至可以使 process
异步,如果它的计算量很大,那将是有益的。处理数百万项会花费一些时间,但是 UI 根本不会阻塞。