What does a Web Worker do?
What a Web Worker is
A Web Worker is a separate background JavaScript thread that runs in parallel with the main (UI) thread.
It has no access to the DOM, but it can:
- perform heavy computations (for example, parsing, encryption, sorting large arrays),
- exchange messages with the main thread via
postMessage, - work independently of the interface, without "freezing" the site.
How it works
Picture the browser:
- The main thread handles the DOM, events, rendering, and the interface.
- The worker thread is a background thread that runs JS code.
They communicate with each other through message passing, like two separate processes.
Usage example
1. The worker.js file
// This code runs in a separate thread
self.onmessage = (event) => {
const n = event.data;
let sum = 0;
for (let i = 0; i < n; i++) {
sum += i;
}
// Send the result back to the main thread
self.postMessage(sum);
};2. In the main file (for example, main.js)
const worker = new Worker('worker.js');
// Send the task
worker.postMessage(1e8);
// Get the result
worker.onmessage = (event) => {
console.log('Result:', event.data);
};
// You can listen for errors
worker.onerror = (err) => {
console.error('Error in the worker:', err);
};Now the sum from 0 to 100 million is computed in the background, and the interface stays smooth and responsive.
Exchanging data
-
Data is passed through serialization (structured clone).
-
Large data can be passed without copying using Transferable objects:
javascriptconst buffer = new ArrayBuffer(1024); worker.postMessage(buffer, [buffer]); // Transfer ownership
After the transfer, buffer becomes unavailable in the main thread (it was passed by reference).
Limitations
- No access to:
document,window,alert,localStorage- the DOM directly (only data can be passed)
- Available:
fetch,setTimeout,Promise,WebSocket,IndexedDB- importing other scripts via
importScripts()
Types of workers
| Type | Description |
|---|---|
| Dedicated Worker | Works with only one main thread (the most common case) |
| Shared Worker | Can be used by several pages or tabs of the same domain |
| Service Worker | A proxy between the app and the network: cache, offline mode, push notifications |
When to use a Web Worker
Good fit:
- Processing large data (JSON, CSV, images, matrices)
- Generating thumbnails, encoding images
- Cryptography, hashing (SHA-256, PBKDF2)
- Complex algorithms (pathfinding, sorting, simulations)
- AI inference, ML models in the browser
Not needed:
- For simple requests or light computations
- When access to the DOM matters
Modern improvements
-
Comlinkis a library that simplifies working with workers:javascriptimport { wrap } from 'comlink'; const worker = new Worker('worker.js'); const api = wrap(worker); // You can just call methods as async functions await api.calculateSomething(123); -
With
ES Modulesyou can create workers withtype: 'module':javascriptconst worker = new Worker('./worker.js', { type: 'module' });
Summary
| What it does | How it helps |
|---|---|
| Runs JS code in a separate thread | Does not block the main Event Loop |
| Exchanges messages with the main thread | Work can be parallelized |
| Has no access to the DOM | Safe and isolated |
| Used for heavy computations | Improves responsiveness and FPS |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.