What does a Web Worker do?
What a Web Worker is
A Web Worker is a separate thread for running JavaScript code, working in parallel with the main thread (the UI thread).
It does not block the interface and can run heavy computations, then pass the result back to the main thread.
The problem without a Web Worker
JavaScript in the browser is single-threaded - everything runs in one thread:
- page rendering
- event handling
- running your code
If you run a heavy loop in that thread:
for (let i = 0; i < 1e9; i++) {}
console.log('Done!');the page will "freeze" - the interface stops responding until the loop finishes, because the Event Loop is busy.
The solution - a Web Worker
With a Web Worker you can move that computation into a separate thread:
// main.js
const worker = new Worker('worker.js');
worker.postMessage(1e9); // send the task
worker.onmessage = (event) => {
console.log('Result:', event.data);
};// worker.js
onmessage = (event) => {
let sum = 0;
for (let i = 0; i < event.data; i++) sum += i;
postMessage(sum); // send the result back
};Now the heavy computation runs in the background, and the UI stays responsive.
How it works under the hood
- The main thread creates a worker via
new Worker('script.js'). - The browser starts a separate JS thread.
- Communication between threads happens through messages (message passing).
- The transfer is asynchronous, data is serialized (structured clone).
- The worker does not have access to the DOM,
window, ordocument.
Exchanging data (message passing)
Communication happens through the postMessage and onmessage events:
// main.js
worker.postMessage({ action: 'sum', a: 5, b: 7 });
// worker.js
onmessage = (e) => {
if (e.data.action === 'sum') {
postMessage(e.data.a + e.data.b);
}
};You can pass:
- strings, numbers, objects
ArrayBuffer,Blob,File,ImageBitmap- even Transferable objects, to pass data without copying it
One-sided limitations
A Web Worker is isolated:
- no access to
document,window,alert(),localStorage - has access to:
fetch,XMLHttpRequest,WebSocket,setTimeout,indexedDB,crypto, etc.
Types of Web Workers
| Type | Where it is used | Features |
|---|---|---|
| Dedicated Worker | One per one | Works only with the script that created it |
| Shared Worker | Several tabs/scripts | One worker for all pages (by origin + URL) |
| Service Worker | Between the browser and the network | Caches requests, works even offline |
Shared Worker example
// shared-worker.js
onconnect = (event) => {
const port = event.ports[0];
port.onmessage = (e) => {
port.postMessage(`Received: ${e.data}`);
};
};Several tabs can connect to the same Shared Worker - for example, to exchange data between tabs.
Service Worker (a special type)
A Service Worker is not just a thread, it's a "proxy" between the browser and the network.
It intercepts HTTP requests, caches responses, and lets an app work offline. (Example: PWA apps, push notifications, background sync.)
Service Worker example
// service-worker.js
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((cached) => {
return cached || fetch(event.request);
})
);
});This means: if there is a cached response, return it, otherwise load it from the network and save it.
Streaming data processing in a worker
A worker can use the Streams and Fetch APIs:
onmessage = async (e) => {
const response = await fetch(e.data.url);
const text = await response.text();
postMessage(text.length);
};This way you can process network data in the background, without blocking the UI at all.
"Parallel" computation example
const workers = Array.from({ length: 4 }, () => new Worker('calc.js'));
let completed = 0;
let result = 0;
workers.forEach((w, i) => {
w.postMessage(i);
w.onmessage = (e) => {
result += e.data;
if (++completed === 4) console.log('Done:', result);
};
});This way computation can be distributed across several threads ("pseudo-parallelism").
When to use Web Workers
| Scenario | Why it's useful |
|---|---|
| Complex computations | JSON parsing, cryptography, machine learning |
| Processing large data | filtering/aggregating arrays, processing CSV |
| Working with images | compression, filters, thumbnail generation |
| Games / animation | physics calculations without interface lag |
| WebSocket + data analysis | streaming processing |
A simple analogy
Imagine the browser is a kitchen.
- The main thread (the main JS) is the chef who cooks the dish and serves the guests.
- The Web Worker is an assistant at another station who chops vegetables.
The chef gives a task -> the assistant does it in the background -> returns the result. No one gets in anyone's way.
Summary
| Component | What it does |
|---|---|
| Web Worker | A separate thread for running code |
| Main advantage | Does not block the UI |
| Data exchange | Through postMessage / onmessage |
| Limitations | No access to the DOM, window, document |
| Types | Dedicated, Shared, Service Worker |
| Main uses | Background computation, caching, offline mode, synchronization |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.