JavaScript · Question 92
When should you use a Web Worker instead of ordinary async JavaScript on the main thread?
Direct answer
Use async APIs to avoid waiting synchronously on I/O, but use a Worker when substantial JavaScript computation itself would occupy the main thread; a worker executes in a separate worker agent/global environment and communicates by messages rather than sharing the DOM.
Turning a CPU-heavy loop into async function calculate(){ ... } does not move the loop off the main thread. If the loop runs for 200 ms without yielding, the UI can still freeze for that period. async changes Promise-based control flow; it does not create another execution thread.
A dedicated Worker runs code in a separate worker environment. The page communicates with it using postMessage() and message events. This makes workers appropriate for CPU-heavy parsing, image/data transforms, compression, large calculations, and similar tasks when main-thread responsiveness matters.
- Workers do not have normal direct access to the page DOM.
- Communication has serialization or transfer costs, so tiny work can be slower when moved to a worker.
- Measure the real bottleneck before introducing worker architecture; network waiting is usually not fixed by adding a worker.