Html Web Worker


The Web Worker API allows us to run any time-consuming complex job in the background. Since JavaScript is a single-threaded language because of one call stack hence it doesn't allow us to run any job in the background.

For example, suppose you want to calculate the prime numbers in a given range and if it takes time in prime number calculation, you won't be able to scroll or click on the page at that time. You might be getting a “page unresponsive” error message.


Tip:This kind of job can be done in the background while the person using your page is in the foreground. We can say Web Worker API creates a background thread to run any time-consuming or complex job.

Steps to use Web Workers

1. Create a web worker object.

2. Assign a job to a web worker that needs to be run ithe n background.

worker = new Worker(blobURL);

3. Start the web worker.

worker.postMessage(message)

4. As soon as the web worker is done, it notifies back to web page.

worker.onmessage = receivedWorkerResponse;

Example


Calculate prime numbers

Here is the below example to calculate the prime numbers fall in a given range that is 1 to 30000000. When you click on the search button, the page will be unresponsive for couple of seconds. You won't be able to click or page scroll at that time.

If you take a close look at the JavaScript code, when you click on the search button a JavaScript function searchPrimeNumber() is invoked. Since the code is running under the main thread and it gets blocked while calculating prime numbers hence page gets unresponsive.



Calculate a prime number in the background using Web Worker.

When you want to run a job in the background, you create an object of a Worker. Let's solve the above problem by using Web Worker.

If you look the closer look, JavaScript code is not running under the main thread. We have created a worker object and passed the job as a parameter to the worker.

Web page and web worker both communicate to each other by posting a message to each other using the postMessage() method. As soon as we call worker.postMessage(), means the web page sends a command to the worker to start running the job. If we call postMessage() from the worker, a response gets sent out from worker to web page that is handled by receivedWorkerResponse callback method.

html5 web worker running process