Html Web Worker
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.
3. Start the web worker.
4. As soon as the web worker is done, it notifies back to web page.
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.
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.
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.