The single thread problem
JavaScript on a page runs on one main thread that also handles rendering and input. A long computation blocks that thread, freezing scroll and clicks.
What a worker is
A Web Worker runs a script on a separate background thread. It has no access to the DOM, but it can do math, parse data, or compress files without stalling the UI.
Communication
The worker and page do not share memory by default. They talk by postMessage, and each side listens for a message event. Data is copied between threads using structured cloning, or transferred for large buffers.
When to use one
- CPU heavy work like image processing or large sorts.
- Parsing big JSON or CSV payloads.
- Anything that would otherwise drop frames.
Workers have startup cost and message overhead, so they suit sustained work rather than tiny tasks.
Key idea
A Web Worker moves heavy computation to a background thread and communicates via postMessage, keeping the main thread free for rendering and input.