我有一个后台函数,它解析了大量文件数组中的数据。消耗单个文件的时间可能很长,所以我的函数有时可以将JS引擎捆绑2-3秒。
for (let x = 0; x <= dataView.byteLength - 1; x++) strView += String.fromCharCode(dataView.getUint8(x))我并不需要更快的运行,这是一个低优先级的后台过程。我需要的是这个函数(它是一个通过void调用的异步函数,而不是等待)在处理单个文件时一次不阻塞其他函数2-3秒。
是否有一种方法可以修改这个for循环,以便有效地授予JS事件循环权限,以便在上面的"for“循环中执行其他任务?我试着在循环中经常等待一个简短的承诺,但这似乎并没有屈服。我想要做的事情(防止后台进程阻塞更高的优先级)是否真的只能通过像Web工作人员那样真正的多线程/任务来完成?
发布于 2022-03-07 03:37:28
v2.0
function sleep(fff) {
return new Promise(rs => setTimeout(rs, fff));
}
async function slow(count, callback, threshold = 10000) {
var i = 0;
while (i < count) {
callback(i++);
if (i % threshold === 0) {
await sleep(1);
}
}
}
var strView = '';
slow(dataView.byteLength, x => strView += String.fromCharCode(dataView.getUint8(x))).then(() => {
console.log(strView);
});https://stackoverflow.com/questions/71374781
复制相似问题