mc0de
Advanced HTML · Lesson 12 of 13

Web Workers

Keep your websites responsive while JavaScript handles demanding tasks! Learn how background workers process calculations and send results back to the main page.

Web Workers APIBackground Tasks postMessage()Live Calculations
● ● ●   web-worker.js
const worker =
  new Worker("worker.js");

worker.postMessage(1000);

worker.onmessage = (event) => {
  console.log(event.data);
};
✓ Background processing · Responsive interface
01 / Getting Started

Why Does a Webpage Sometimes Freeze?

JavaScript on a webpage usually runs on the main thread. That thread also handles important browser tasks, including responding to user input and updating the interface.

When a long calculation monopolizes the main thread, the page may become slow or unresponsive.

Web Workers let you run JavaScript on another thread so demanding calculations don’t have to block the main page.

Remember: Workers are especially useful for CPU-intensive work. They aren’t necessary for every small calculation.
02 / Creating a Worker

Meet the Worker Constructor

In a typical project, you create a separate JavaScript file for the worker and connect to it from your webpage.

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

worker.postMessage(50000);
worker.js
self.onmessage = function(event) {
  const number = event.data;
  const answer = number * 2;

  self.postMessage(answer);
};

The worker receives data, performs its calculation, and sends the result back to the main page.

Workers are subject to browser security and same-origin rules. Serve your project through a development server or HTTPS instead of assuming local file URLs will work.

03 / Sending Messages

Communicate with postMessage()

The main page and a dedicated worker communicate by sending messages. They don’t directly share ordinary JavaScript variables.

Receive a result on the main page
worker.addEventListener("message", function(event) {
  console.log("Worker result:", event.data);
});

You can send numbers, strings, arrays, and many structured objects. The browser typically uses the structured clone algorithm to transfer data between contexts.

Useful idea: Send an object such as {type:"progress",percent:50} so the main page knows whether a message represents progress or a final result.
04 / Worker Limitations

What Can’t a Worker Do?

A dedicated worker doesn’t have direct access to the webpage’s DOM. It can’t call document.getElementById() to change a heading or button.

Instead, the worker sends a message and the main page updates the interface.

Update the page after receiving data
worker.addEventListener("message", function(event) {
  document.getElementById("result").textContent =
    event.data;
});

Workers have access to several web APIs, but not all APIs available in a window. Keep DOM manipulation in the main page.

05 / Stopping a Worker

Use terminate() to Stop Processing

Sometimes visitors need to cancel a long-running calculation. The main page can stop a worker using terminate().

Stop a background task
worker.terminate();

Termination stops the worker without waiting for its current calculation to finish. To start again, create a new worker.

It’s also good practice to handle worker errors and release worker resources after a task is complete.

06 / Interactive Demonstration

Calculate Prime Numbers in the Background

A prime number is a whole number greater than 1 with no positive divisors other than 1 and itself.

Try counting the prime numbers up to a chosen limit. While the worker calculates, you can still interact with the rest of the page.

Ready to calculate.

Results will appear here.

Responsiveness button presses: 0

Experiment: Start a calculation and click Test Responsiveness. The click counter should continue responding while the worker calculates.
07 / Workers in Real Projects

When Should You Use Them?

Web Workers are useful for image processing, data analysis, large calculations, complex parsing, and other CPU-heavy tasks.

  • Keep the main thread available for interface updates.
  • Send progress messages during long operations.
  • Validate inputs and limit computational work.
  • Handle errors and allow users to cancel tasks.
  • Terminate workers when they are no longer needed.
  • Remember that workers still consume CPU and memory.

A Web Worker is different from a Service Worker: Web Workers help with background computation, while Service Workers are designed around capabilities such as network interception and offline caching.

🚀 mC0de Challenge

Build a Background Prime Calculator

Create an app that counts prime numbers without locking up the interface.

Your Mission

  1. Create a number input for the calculation limit.
  2. Add a Start Calculation button.
  3. Create a Web Worker to perform the calculation.
  4. Send the calculation limit using postMessage().
  5. Receive progress updates and display them in a progress bar.
  6. Display the final prime count when processing finishes.
  7. Add a Stop button that terminates the worker.
Extra challenge: Add a button that updates a click counter during processing to demonstrate that the interface remains responsive.
💻 Interactive HTML Sandbox

Build Your Background Calculator!

Edit the code and click Run Code. The starter shows how to create a worker from a Blob; the solution adds live progress, cancellation, and a responsiveness counter.

Live Result
Sandbox note: This example creates a real worker, but some browsers or website security policies block Blob workers in isolated previews. If worker creation is blocked, test the copied code in a normal HTTPS development page.
Lesson 12 Recap

What You’ve Learned

You’re Building More Responsive Applications!

You’ve learned how background JavaScript processing can improve the experience of a busy webpage.

  • Why heavy calculations can freeze the main thread.
  • How to create a dedicated Web Worker.
  • How to exchange messages using postMessage().
  • How to display worker progress and results.
  • How to stop workers and handle errors.

Next up: Server-Sent Events — learn how servers can stream live updates to a webpage!

Your Learning Journey

0 / 13 Completed

Keep going! You’re almost finished with Advanced HTML!

🎉

Nice Work!

You've learned how to create Web Workers, run demanding calculations in the background, exchange messages, display progress, and stop tasks. You're one lesson away from completing Advanced HTML!