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.
const worker =
new Worker("worker.js");
worker.postMessage(1000);
worker.onmessage = (event) => {
console.log(event.data);
};
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.
Meet the Worker Constructor
In a typical project, you create a separate JavaScript file for the worker and connect to it from your webpage.
const worker = new Worker("/worker.js");
worker.postMessage(50000);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.
Communicate with postMessage()
The main page and a dedicated worker communicate by sending messages. They don’t directly share ordinary JavaScript variables.
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.
{type:"progress",percent:50} so the main page knows whether a message represents progress or a final result.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.
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.
Use terminate() to Stop Processing
Sometimes visitors need to cancel a long-running calculation. The main page can stop a worker using terminate().
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.
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.
Results will appear here.
Responsiveness button presses: 0
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.
Build a Background Prime Calculator
Create an app that counts prime numbers without locking up the interface.
Your Mission
- Create a number input for the calculation limit.
- Add a Start Calculation button.
- Create a Web Worker to perform the calculation.
- Send the calculation limit using
postMessage(). - Receive progress updates and display them in a progress bar.
- Display the final prime count when processing finishes.
- Add a Stop button that terminates the worker.
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.
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 CompletedKeep 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!


