HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

HTML Web Workers API

The HTML Web Workers API is a feature provided by web browsers that enables the use of separate JavaScript threads, known as web workers, to execute scripts concurrently in the background.

What is a Web Worker?

A HTML Web Worker is a JavaScript feature that allows you to run scripts in the background, separate from the main execution thread of a web page

Types of Web Workers:

Dedicated Web Workers:

  • Dedicated Web Workers are created by the main thread and have a one-to-one relationship with the creating script.
  • They have their own global context and can communicate with the main thread through the use of message passing.

Example

// Creating a dedicated Web Worker
var worker = new Worker('worker.js');

// Sending a message to the Web Worker
worker.postMessage('Hello from the main thread!');

// Handling messages from the Web Worker
worker.onmessage = function(event) {
    console.log('Message received from Web Worker:', event.data);
};    
You can click on above box to edit the code and run again.

Output

In this example, the worker.js file would contain the code that the Web Worker executes.

Shared Web Workers (less common):

  • Shared Web Workers are designed for scenarios where multiple scripts from different windows or iframes need to communicate with the same worker.
  • They have a shared global context that can be accessed by multiple scripts. Example of creating a shared Web Worker:

Example

// Creating a shared Web Worker
var sharedWorker = new SharedWorker('shared-worker.js');

// Getting the port for communication
var workerPort = sharedWorker.port;

// Sending a message to the shared Web Worker
workerPort.postMessage('Hello from the main thread!');

// Handling messages from the shared Web Worker
workerPort.onmessage = function(event) {
    console.log('Message received from Shared Web Worker:', event.data);
};
You can click on above box to edit the code and run again.

Output

In this example, the shared-worker.js file would contain the code that the Shared Web Worker executes.

Web Workers operate in a separate thread with its own context, which means they cannot directly access the DOM or manipulate the UI. Communication between the main thread and Web Workers is achieved through message passing, allowing data to be exchanged without the risk of race conditions or shared memory issues.

Create a Web Worker File

To create a Web Worker file we need to create an external JavaScript file.

Here we have created a web worker file for calculating the square of the number. And saved it with the name "worker.js"

Example

onmessage =function(event){  
var num= event.data;  
var sqr=num*num;  
var result="";  
for(var i=1;i<=sqr; i++)  
{  
result= "Sqaure result is:"+ " "+i;  
}  
postMessage(result);  
}  
You can click on above box to edit the code and run again.

Output

Creating the Web Worker Object:

In above "worker.js" file, we have created the JS file for web Worker now it needs to call on an HTML file. To create the web worker object, you need to call the Worker() constructor.

Following is the syntax to call and create the object of Web Worker:

Example

var worker= new Worker('worker.js');  
You can click on above box to edit the code and run again.

Output

Terminating the Web Worker:

If you want to immediately terminate the currently running worker in the main thread, then you can terminate it by calling the terminate() method of Web Worker. Here is the syntax for web worker termination:

Example
worker.terminate();   
You can click on above box to edit the code and run again.

Output

Web Worker can be terminate in worker thread also by calling the close() method.

Full Web Worker Example Code

We have already seen the Worker code in the .js file. Below is the code for the HTML page:

Example

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>

<script>
var w;

function startWorker() {
  if (typeof(Worker) !== "undefined") {
    if (typeof(w) == "undefined") {
      w = new Worker("demo_workers.js");
    }
    w.onmessage = function(event) {
      document.getElementById("result").innerHTML = event.data;
    };
  } else {
    document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
  }
}

function stopWorker() {
  w.terminate();
  w = undefined;
}
</script>

</body>
</html>
You can click on above box to edit the code and run again.

Output

Browser Support

The numbers in the table specify the first browser version that fully support Web Workers.

API Web Workers
Google_Chrome 4.0
Firefox 3.5
microsoft-edge 10.0
opera. 11.5
safari 4.0