HTML Web Workers (Background Processing)
HTML Web Workers: Background Processing
JavaScript normally runs on a single main thread, which also handles rendering and user interaction — so a slow, CPU-heavy calculation can freeze the entire page. Web Workers solve this by running a separate JavaScript file on its own background thread, completely independent of the UI, so heavy work no longer blocks scrolling, clicking, or animations.
How Web Workers Communicate
A worker cannot directly access the DOM, window, or the main thread's variables. Instead, the main script and the worker communicate exclusively by sending messages back and forth using postMessage() and listening with the onmessage event handler.
Creating a Worker
A worker is created by pointing the Worker constructor at a separate JavaScript file. That file runs in its own isolated global scope, often referred to as self inside the worker.
Sending and Receiving Data
Data passed through postMessage() is copied (not shared by reference) between the threads, using an algorithm called structured cloning, so both sides can safely use the same data without race conditions.
Terminating a Worker
Once a worker's job is done, calling worker.terminate() from the main thread (or self.close() from inside the worker) shuts it down and frees its resources.
When to Use Web Workers
- Heavy mathematical calculations (image/video processing, encryption, large dataset sorting).
- Parsing very large JSON or CSV files without freezing the UI.
- Real-time data processing, such as live chart updates from a large stream.
- Any task that would otherwise cause visible lag or a "page not responding" warning.
Limitations
No DOM access, no access to most main-thread-only APIs (like window or document), and each worker has some memory and startup overhead — so workers are best reserved for genuinely expensive tasks, not everyday code.
Press Run to execute.
Press Run to execute.
Write a worker.js file that receives a number N via postMessage, sums all integers from 1 to N in a loop, and sends the total back to the main thread. Then write the main-thread code that creates the worker, sends N = 1000000, and logs the result.
Press Run to execute.
Show expected output
The worker computes the sum from 1 to 1,000,000 and the main thread logs the returned total.This is a self-check — compare your result with the expected output above.
Was this page helpful?