JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Web Worker API


Web applications are becoming more complex, and JavaScript often needs to handle heavy tasks such as calculations, data processing, or API calls. Running these tasks directly on the main thread can slow down the page, making it unresponsive.

The Web Worker API solves this problem by allowing JavaScript to run scripts in the background without blocking the main thread.

What Is a Web Worker?

A Web Worker is a separate JavaScript thread that runs alongside your main web page. It can:

  • Perform tasks without blocking the user interface

  • Communicate with the main thread using messages

  • Improve performance for CPU-intensive operations

Important: Web Workers cannot access the DOM directly. They work independently and communicate with the main page via messages.

Types of Web Workers

  1. Dedicated Workers

    • Only connected to the script that created them.

    • Most commonly used.

  2. Shared Workers

    • Can be accessed by multiple scripts from different windows or tabs.

    • Useful for shared background tasks.

In this tutorial, we focus on dedicated workers.

Creating a Web Worker

A Web Worker is created using the Worker constructor.

Step 1: Create a worker script

worker.js

// Worker script - runs in a separate thread
self.onmessage = function(event) {
    const number = event.data; // Receive data from main thread
    let result = 0;
    // Perform a heavy calculation (sum from 1 to number)
    for(let i = 1; i <= number; i++) {
        result += i;
    }
    // Send result back to main thread
    self.postMessage(result);
};

Step 2: Create the main script

<input type="number" id="num" placeholder="Enter a number">
<button id="calculateBtn">Calculate Sum</button>
<p id="output"></p>

<script>
const output = document.getElementById("output");
const worker = new Worker("worker.js"); // Create a worker

document.getElementById("calculateBtn").addEventListener("click", function() {
    const num = document.getElementById("num").value;
    // Send data to worker
    worker.postMessage(Number(num));
    output.textContent = "Calculating...";
});

// Receive result from worker
worker.onmessage = function(event) {
    output.textContent = "Result: " + event.data;
};
</script>

Explanation:

  • worker.postMessage() sends data from the main thread to the worker.

  • self.onmessage in the worker receives the data.

  • self.postMessage() sends the result back.

  • worker.onmessage in the main thread handles the response.

The main thread remains responsive while the calculation runs in the background.

Terminating a Worker

You can stop a worker when it’s no longer needed using terminate().

worker.terminate(); // Stops the worker immediately

Tip: Always terminate workers after use to free system resources.

Handling Errors in Workers

You can listen for errors using onerror.

worker.onerror = function(event) {
    console.error("Worker error:", event.message);
};

Explanation:

  • event.message shows the error message.

  • event.filename shows the script where the error occurred.

  • event.lineno shows the line number.

Using Workers for Heavy Computation

Web Workers are ideal for long loops, complex calculations, or data processing.

Example: Factorial Calculation

worker.js

self.onmessage = function(event) {
    const n = event.data;
    let factorial = 1;
    for(let i = 2; i <= n; i++) {
        factorial *= i;
    }
    self.postMessage(factorial);
};

main.js

const worker = new Worker("worker.js");

worker.onmessage = function(event) {
    console.log("Factorial result:", event.data);
};

worker.postMessage(10); // Calculate factorial of 10

The calculation runs without freezing the main page.

Communicating with Workers

Communication between main thread and worker is always via message passing.

  • Main to Worker: worker.postMessage(data)

  • Worker to Main: self.postMessage(data)

Example:

// main.js
worker.postMessage({ type: "greet", name: "Vicky" });

// worker.js
self.onmessage = function(event) {
    const data = event.data;
    if(data.type === "greet") {
        self.postMessage("Hello, " + data.name + "!");
    }
};

Explanation:

  • You can send objects or strings between main thread and worker.

  • Workers don’t share memory with the main thread.

Limitations of Web Workers

  1. No DOM access – cannot manipulate HTML elements directly.

  2. Limited API access – workers cannot use some browser features like alert() or document.

  3. Communication overhead – sending large data back and forth can be slower.

  4. Same-origin policy – worker scripts must be on the same domain or server.

Despite these limitations, Web Workers significantly improve performance for heavy tasks.

Real-World Use Cases

  • Calculating large datasets in the background.

  • Image or video processing in the browser.

  • Real-time games or simulations.

  • Performing AI or machine learning tasks on the client side.

  • Fetching and processing data from APIs without freezing UI.

Summary of the Tutorial

The Web Worker API is a powerful tool to run background tasks in JavaScript. Key points to remember:

  • Use Worker() to create a new worker.

  • Communicate using postMessage() and onmessage.

  • Terminate workers with terminate() when done.

  • Handle errors using onerror.

  • Web Workers cannot access the DOM directly, but they keep your UI responsive.

Mastering Web Workers allows you to build fast, smooth, and interactive web applications, even for heavy computations or real-time tasks.


Practice Questions

  1. Create a Web Worker that calculates the sum of numbers from 1 to a user-entered value and sends the result back to the main thread.

  2. Write a script that calculates the factorial of a number using a Web Worker without freezing the main page.

  3. Implement a Web Worker that reverses a long string sent from the main thread and returns the reversed string.

  4. Create a worker that counts the number of vowels in a given text input and sends the count back to the main thread.

  5. Write code to terminate a Web Worker after it finishes processing a large array of numbers.

  6. Implement a Web Worker that multiplies each element in an array by 2 and returns the new array to the main thread.

  7. Create a worker that generates a random large array of numbers and calculates the maximum value, sending the result to the main thread.

  8. Write a script where the main thread sends an object containing {name, age} to a worker, and the worker responds with a greeting message.

  9. Implement error handling in a Web Worker that divides two numbers and returns a message if division by zero occurs.

  10. Create a Web Worker that simulates a countdown timer from a given number and posts the remaining seconds back to the main thread at 1-second intervals.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top