Web Workers

Web Workers are a feature in HTML5 that allows you to run JavaScript code in the background, separate from the main execution thread of your web application. This helps prevent the user interface from becoming unresponsive during computationally intensive tasks or large data processing.


  1. Main thread vs. Worker thread: A web application's JavaScript code runs on the main thread by default. When you create a Web Worker, you create a separate worker thread that can execute JavaScript code without interfering with the main thread. This separation allows your application to remain responsive, even when performing complex tasks.

  2. Communication between threads: The main thread and worker thread communicate by sending messages to each other. The `postMessage()` method is used to send messages, and the `message` event is used to receive them. This ensures that data is passed between threads without causing blocking.


worker.js (worker script)

self.addEventListener('message', (event) => {
  const number =;
  const result = number * 2; // Simple calculation for demonstration
  self.postMessage(result); // Send the result back to the main thread

index.html (main HTML file)

<!DOCTYPE html>
  <title>Web Workers Example</title>
  <input type="number" id="inputNumber" placeholder="Enter a number">
  <button onclick="startWorker()">Start Worker</button>
  <p id="result"></p>

    let worker;

    function startWorker() {
      if (typeof(Worker) !== 'undefined') {
        if (typeof(worker) == 'undefined') {
          worker = new Worker('worker.js'); // Create a new Web Worker
        worker.onmessage = (event) => {
          document.getElementById('result').innerHTML =; // Display the result from the worker

        const number = document.getElementById('inputNumber').value;
        worker.postMessage(number); // Send the input number to the worker
      } else {
        alert('Web Workers are not supported in your browser');

In this example, when the user clicks the "Start Worker" button, the `startWorker()` function is called. This function creates a new Web Worker and sets up the `message` event listener. Then, it sends the input number to the worker. The worker script receives the message, performs a simple calculation, and sends the result back to the main thread. The main thread then displays the result on the page.

This is just a simple example to demonstrate the concept of Web Workers. In a real-world scenario, the worker thread can be used to perform more complex tasks, like image processing, data manipulation, or running algorithms, without affecting the responsiveness of the main thread.

Was this page helpful?