Skip to content

Web Worker

In one line

A Web Worker lets you run JavaScript in a background thread, keeping the main UI thread responsive.

In simple words

JavaScript is single-threaded — long-running computations block the UI and make the page feel frozen. Web Workers solve this by letting you run a script in a separate background thread. The main thread and the worker communicate by passing messages, not by sharing variables.

Workers are perfect for heavy tasks: parsing large JSON, image processing, sorting big arrays, complex calculations. The main thread posts a message with the input, the worker computes, and posts the result back. The UI stays smooth because the heavy work happens off the main thread.

Workers cannot access the DOM or window object directly — they live in a different context. Data passed between threads is copied (or transferred for ArrayBuffer) rather than shared. SharedArrayBuffer and the Atomics API enable true shared-memory workers for advanced cases.

Example

javascript
// main.js
const worker = new Worker("heavy.js");
worker.postMessage({ numbers: [5, 3, 8, 1, 9] });
worker.onmessage = (e) => console.log("Sorted:", e.data);

// heavy.js (runs in background thread)
onmessage = (e) => {
  const sorted = e.data.numbers.sort((a, b) => a - b);
  postMessage(sorted);
};

The main thread creates a Worker, sends data via postMessage, and receives the result. The sort runs off the main thread so the UI stays responsive.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary