A Web Worker is a JavaScript API that allows you to run a script operation in the background, separate from the main execution thread of a web page. This allows for long-running scripts to be executed without freezing the user interface, making the page more responsive. Web Workers can be used for tasks such as image or video processing, or for creating complex animations, without negatively impacting the performance of the page. Web Workers are supported in most modern web browsers.

Example of Web Worker In JavaScript

Here’s an example of how to use a Web Worker in JavaScript:

// worker.js
self.addEventListener('message', (e) => {
  const data = e.data;
  // do some time-consuming operation
  const result = heavyComputation(data);
// main.js
const worker = new Worker('worker.js');
worker.addEventListener('message', (e) => {
worker.postMessage({data: 'hello'});

In this example, we have two files: worker.js and main.js. worker.js is the script that will be run in the background by the Web Worker. It listens for a message event, which is sent from the main script. It receives the data sent by the main script, does some time-consuming operation on it and then sends the result back to the main script using self.postMessage(result).

main.js creates a new instance of the Worker object, passing in the path to the worker.js script. It then listens for message events, which will be sent by the worker when the computation is complete. It sends the data to the worker using worker.postMessage({data: ‘hello’}).

This way, the heavy computation is not blocking the main thread, and the web page remains responsive.

Also Read:

Categorized in: