What is a web worker? How to use it? and Example

sharath .v
2 min readOct 25, 2023

--

A web worker is a JavaScript script executed in the background, independently of the main thread. Web workers provide a way to run scripts in the background to perform tasks without blocking the main thread, which is crucial for keeping web applications responsive. They are particularly useful for handling computationally expensive tasks, such as large data processing or complex calculations.

Here’s a basic overview of web workers and how to use them:

1. Creating a Web Worker:

A web worker is created by instantiating the Worker object and specifying the script file that the worker will run. The script file is a separate JavaScript file.

// main.js (your main application file)
const myWorker = new Worker('worker.js');

2. Handling Communication:

Communication between the main thread and the worker is done using the postMessage method. You can send data to the worker, and the worker can send messages back.

// main.js
myWorker.postMessage('Hello from the main thread!');

myWorker.onmessage = function (event) {
console.log('Received message from worker:', event.data);
};

3. Processing in the Web Worker:

The web worker script (worker.js) will handle the computations or tasks without blocking the main thread.

// worker.js
onmessage = function (event) {
console.log('Received message from main thread:', event.data);

// Perform some heavy computation
const result = event.data * 2;

// Send the result back to the main thread
postMessage(result);
};

Example:

Let’s consider a simple example where the main thread sends a number to the worker, and the worker multiplies it by 2 and sends the result back.

// main.js
const myWorker = new Worker('worker.js');

myWorker.postMessage(5);

myWorker.onmessage = function (event) {
console.log('Received result from worker:', event.data);
};
// worker.js
onmessage = function (event) {
console.log('Received number from main thread:', event.data);

// Perform computation
const result = event.data * 2;

// Send result back to the main thread
postMessage(result);
};

In this example, when the main thread sends the number 5 to the worker, the worker multiplies it by 2 and sends the result (10) back to the main thread.

Web Worker in React

Remember that web workers have some limitations, such as limited access to the DOM and shared data between the main thread and the worker through serialization. They are most effective for CPU-bound tasks and should be used judiciously based on the application’s needs.

--

--