HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

Web Worker API

A Web Worker is a JavaScript script that runs in the background, independently of other scripts, without affecting the performance of the user interface. This allows you to perform heavy calculations or data processing without "freezing" the browser window.


Performance Comparison Lab

Try the two scenarios below. Observe how the spinning circle behaves during the heavy 1-billion iteration loop:

Status: Ready
⚠️ UI FROZEN! Mouse/Scroll won't work...

What is a Web Worker?

Usually, JavaScript is Single-Threaded, meaning it can only do one thing at a time. If you run a script that takes 5 seconds to finish, the browser cannot react to user clicks or scroll events during those 5 seconds. Web Workers solve this by creating a Background Thread.


Creating a Web Worker

First, you need a separate JavaScript file for your worker (e.g., worker.js):

// Inside worker.js
onmessage = function(e) {
    let result = e.data[0] * e.data[1];
    postMessage(result);
}

Then, in your main HTML file, you create the worker object and listen for messages:

// Main script
let myWorker = new Worker("worker.js");

// Send data to worker
myWorker.postMessage([10, 20]);

// Receive data from worker
myWorker.onmessage = function(e) {
    console.log("Result received: " + e.data);
};

Terminating a Worker

If you need to stop a worker immediately, use the terminate() method. This kills the background process and frees up resources.

myWorker.terminate();
myWorker = undefined; // Cleanup

Limitations of Web Workers

Because they run in a separate thread, Web Workers do **not** have access to several browser features:

  • The Window object
  • The Document object (the DOM)
  • The Parent object
Note: Workers are best used for Pure Logic (math, data sorting, image processing). They cannot change the HTML directly; they must send the result back to the main script.

Key Points to Remember

  • Web Workers provide true multi-threading for the web.
  • They prevent heavy tasks from blocking the Main Thread (UI).
  • Communication happens via postMessage().
  • Workers live in separate files and have their own scope.
  • They cannot access the DOM directly.
  • They must be terminated when no longer needed to save battery/RAM.