Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

58
Views
How to keep a slow async function from blocking others?

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?

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
});
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.