JavaScript: Run a function in a separate thread by using a Web Worker, allowing long running functions to not block the UI
JavaScript: Exercise-151 with Solution
Run Function in Web Worker
Write a JavaScript program to run a function in a separate thread using a Web Worker. This allows long running functions to not block the UI.
Note: Create a new Worker using a Blob object URL, the contents of which should be the stringified version of the supplied function. Immediately post the return value of calling the function back. Return a promise, listening for onmessage and onerror events and resolving the data posted back from the worker, or throwing an error.
Since the function is running in a different context, closures are not supported. The function supplied to `runAsync` gets stringified, so everything becomes literal. All variables and functions must be defined inside.
- Create a new Worker() using a Blob object URL, the contents of which should be the stringified version of the supplied function.
- Immediately post the return value of calling the function back.
- Return a new Promise(), listening for onmessage and onerror events and resolving the data posted back from the worker, or throwing an error.
Sample Solution:
JavaScript Code:
Sample Output:
1000 undefined
Flowchart:

Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript program that offloads a CPU-intensive calculation (e.g., prime number generation) to a Web Worker and returns the result to the main thread.
- Write a JavaScript program that creates a Web Worker to process large JSON data, sending periodic progress updates back to the UI.
- Write a JavaScript program that utilizes transferable objects (e.g., ArrayBuffer) with a Web Worker to optimize data processing speed.
- Write a JavaScript program that spawns a Web Worker to perform a recursive computation (like calculating factorial for a large number) without blocking the UI.
- Write a JavaScript program that demonstrates error handling in a Web Worker by intentionally triggering an error and catching it in the main thread.
Go to:
PREV : Run Promises in Series.
NEXT : Round Number to Digits.
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.