I have a background function which parses a lot of data from an array of files. The time to consume a single file can be long, so my function can sometimes tie up the JS engine for 2-3 seconds.
for (let x = 0; x <= dataView.byteLength - 1; x++) strView += String.fromCharCode(dataView.getUint8(x))
I don't really need this to run more quickly, it's a low priority background process. What I do need is for this function (which is an async function called via void and not await) to not block other functions for 2-3 seconds at a time during processing of a single file.
Is there a way to modify this for loop to effectively give the JS event loop permission to do other tasks in the middle of the above "for" loop? I tried awaiting a short promise every so often in the loop, but that doesn't seem to yield. Is can what I'm seeking to do (to prevent a background process from blocking higher priorities) really only be accomplished through something like a Web Worker for true multi-threading/tasking?
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);
});