HTML5 – Web workers

Web workers are background threads that can be used to run tasks concurrently with the main JavaScript thread. HTML5 introduced the Worker object, which allows web applications to create and communicate with web workers.

Web workers are useful for running tasks that are time-consuming or CPU-intensive, such as image processing, data crunching, or network operations, in the background to improve the performance of the web application.

To use a web worker, you need to create a JavaScript file that contains the code for the worker and use the Worker constructor to create a new worker object:

var worker = new Worker('worker.js');

In this example, the Worker constructor is used to create a new worker object that runs the code in the worker.js file.

To communicate with the worker, you can use the postMessage and onmessage methods of the worker object:

// Send a message to the worker
worker.postMessage('Hello worker!');

// Receive a message from the worker
worker.onmessage = function(event) {
  console.log(event.data); // Outputs 'Hello main thread!'
};

In this example, the postMessage method is used to send a message to the worker, and the onmessage event handler is used to receive a message from the worker. The event object passed to the event handler has a data property that contains the data of the message.

Here is an example of how to use web workers to perform a long-running task:

// worker.js
onmessage = function(event) {
  var result = 0;
  for (var i = 0; i < event.data; i++) {
    result += i;
  }
  postMessage(result);
};

// main.js
var worker = new Worker('worker.js');
worker.postMessage(1000000);
worker.onmessage = function(event) {
  console.log(event.data); // Outputs 499999500000
};

In this example, the worker.js file contains the code for the worker that performs a long-running task of adding up the numbers from 0 to 1,000,000. The main.js file creates a worker object and sends a message to the worker to start the task. When the task is completed, the worker sends a message back to the main thread with the result.