On this page9 sections
  1. Learning Objectives
  2. 1. The Problem: a Frozen Page
  3. 2. The Worker File
  4. 3. The Page
  5. 4. The Rules
  6. Common Beginner Mistakes
  7. Practice Questions
  8. Practice Answers
  9. Key Takeaways

Lecture 047: Web Workers API

Category8: Web APIs
Lecture047 of 048
Estimated video length10 min
TargetHTML5 · any modern browser
LevelIntermediate

JavaScript on a page runs on one thread, the same one that handles clicks and scrolling. A long calculation freezes everything until it finishes. A Web Worker runs that work in the background, so the page stays responsive.


Learning Objectives

  • Explain why heavy work freezes a page
  • Start a worker from a separate .js file
  • Send messages to and from a worker with postMessage and onmessage
  • Stop a worker with terminate()

1. The Problem: a Frozen Page

Example: press "Heavy work", then try typing in the box straight away:

html
<input placeholder="Try typing while it works">
<button type="button" onclick="heavy()">Heavy work</button>
<p id="out"></p>

<script>
  function heavy() {
    let total = 0;
    for (let i = 0; i < 2e8; i++) total += i;   // a few seconds of work
    document.getElementById('out').textContent = 'Done: ' + total;
  }
</script>

The input can't respond until the loop ends. That's what workers fix.


The worker examples below need two files, and preview boxes on this page can't load extra files. Save both files in the same folder and open the HTML page through a local web server. In VS Code, the free Live Server extension does this with one click.


2. The Worker File

worker.js holds the heavy job. It listens for a message, works, then posts the answer back.

javascript
// worker.js
onmessage = (event) => {
  const limit = event.data;
  let total = 0;
  for (let i = 0; i < limit; i++) total += i;
  postMessage(total);
};

3. The Page

html
<input placeholder="Typing still works!">
<button type="button" onclick="start()">Heavy work (in a worker)</button>
<button type="button" onclick="stop()">Stop</button>
<p id="out"></p>

<script>
  let worker;

  function start() {
    if (worker) return;                       // already running
    worker = new Worker('worker.js');
    worker.onmessage = (event) => {
      document.getElementById('out').textContent = 'Done: ' + event.data;
      stop();
    };
    worker.postMessage(3e8);                   // send the job
    document.getElementById('out').textContent = 'Working in the background…';
  }

  function stop() {
    if (worker) { worker.terminate(); worker = undefined; }
  }
</script>

Now you can type while it works.


4. The Rules

A worker canA worker can't
Do calculationsTouch the page (document, elements)
Use fetch and timersUse alert or localStorage
Send and receive messagesShare variables with the page directly

Everything goes through messages: postMessage(data) sends, onmessage receives. Data is copied, not shared.


Common Beginner Mistakes

1. Opening the page by double-clicking. Browsers block workers on file://. Use a local server.

2. Trying to change the page from the worker. Send the result back, and let the page update itself.

3. Never terminating. A worker keeps running until terminate() or the page closes.


Practice Questions

  1. Why does a long loop freeze the page?
  2. How do you start a worker from jobs.js?
  3. How does the page send data to a worker?
  4. How does the worker send its result back?
  5. Can a worker change the text of a paragraph directly?
  6. How do you stop a worker?

Practice Answers

  1. Page JavaScript runs on one thread, which also handles clicks, typing and drawing.
  2. const w = new Worker('jobs.js');
  3. w.postMessage(data);
  4. With postMessage(result), received by the page's onmessage.
  5. No. It has no access to the page; it sends a message instead.
  6. w.terminate();

Key Takeaways

  • Workers run heavy JavaScript in the background, keeping the page responsive.
  • new Worker('file.js'), then talk with postMessage / onmessage.
  • Workers can't touch the DOM.
  • They need a web server, not a double-clicked file.