95Implement a Web Worker for CPU-intensive computation
Problem
Heavy computation on the main thread freezes scrolling, typing and animations. Implement createWorkerTask(fn), which runs a self-contained function in a Web Worker and returns:
run(...args): a promise forfn(...args)computed in the worker. Several calls may be in flight at once; each gets its own result.terminate(): stop the worker and reject every pending call with an error named"AbortError".
Errors thrown inside fn must reject the matching run call with an Error that has the same message. fn may be async.
Create the worker from a Blob URL, so no separate file is needed:
const primes = createWorkerTask((limit) => {
const sieve = new Uint8Array(limit + 1);
let count = 0;
for (let i = 2; i <= limit; i++) {
if (sieve[i]) continue;
count++;
for (let j = i * i; j <= limit; j += i) sieve[j] = 1;
}
return count;
});
const count = await primes.run(10_000_000); // the page stays responsiveTry it yourself
Write your solution, run it, then submit to check it against the tests.
Step-by-step
The function must be self-contained (it cannot use variables from its surrounding scope, because the worker is a separate world). Turn it into code with fn.toString() and wrap it in a message handler:
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 3 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.