HTML5 Web Workers
- While the web worker is running in the background you can continue doing whatever you want like clicking, selecting etc.
- Web workers are heavy weight and are not used in large numbers.
- They do not have direct access to the web page and DOM API.
- Web workers cannot block the browser UI but they can consume the CPU cycles and make the system less responsive.
Working of Web Workers
var worker= new Worker ('example.js');
Syntax for importScripts() method:
- postMessage() method helps in communicating between the web worker and its parent page. This method accepts either a string or JSON object as a single argument depending on the browser.
- The onmessage event accesses the message that is passed on by the web worker.
- The web workers cannot stop on their own. They have to be stopped by calling the terminate() method.
- A web worker that is terminated does not respond to the messages or perform any additional computations. A worker can never be restarted instead a new one can be created by using the same URL.
Example : Demonstrating a Web worker for counting numbers
var a = 0;
a = a + 1;
Step 2: Create an HTML file and save the following code
<p>The count is:
The count is: 3
The number in the above output keeps on changing every second.