On this page9 sections
Lecture 047: Web Workers API
| Category | 8: Web APIs |
| Lecture | 047 of 048 |
| Estimated video length | 10 min |
| Target | HTML5 · any modern browser |
| Level | Intermediate |
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
.jsfile - Send messages to and from a worker with
postMessageandonmessage - Stop a worker with
terminate()
1. The Problem: a Frozen Page
Example: press "Heavy work", then try typing in the box straight away:
<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.
// 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
<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 can | A worker can't |
|---|---|
| Do calculations | Touch the page (document, elements) |
Use fetch and timers | Use alert or localStorage |
| Send and receive messages | Share 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
- Why does a long loop freeze the page?
- How do you start a worker from
jobs.js? - How does the page send data to a worker?
- How does the worker send its result back?
- Can a worker change the text of a paragraph directly?
- How do you stop a worker?
Practice Answers
- Page JavaScript runs on one thread, which also handles clicks, typing and drawing.
const w = new Worker('jobs.js');w.postMessage(data);- With
postMessage(result), received by the page'sonmessage. - No. It has no access to the page; it sends a message instead.
w.terminate();
Key Takeaways
- Workers run heavy JavaScript in the background, keeping the page responsive.
new Worker('file.js'), then talk withpostMessage/onmessage.- Workers can't touch the DOM.
- They need a web server, not a double-clicked file.