MediumBrowser APIs📖 Theory Question

What are Web Workers and when should you use them?

💡

Hint

Run JS in a background thread — no DOM access; use postMessage to communicate

Full Answer

Web Workers run JavaScript in a separate background thread — preventing heavy computation from blocking the main thread (UI freezing).

// main.js
const worker = new Worker('worker.js');

// Send data to worker (structured clone — copies data)
worker.postMessage({ array: bigArray, threshold: 50 });

// Receive results
worker.onmessage = (e) => {
  console.log('Result:', e.data.result);
  worker.terminate(); // clean up
};

worker.onerror = (e) => console.error('Worker error:', e.message);

// worker.js — completely separate context
self.onmessage = (e) => {
  const { array, threshold } = e.data;
  // Heavy computation — won't block UI
  const result = array.filter(x => x > threshold).reduce((a,b) => a+b, 0);
  self.postMessage({ result });
};

Limitations: No access to DOM, window, document. Communication only via postMessage. Data is copied (structured clone), not shared (except SharedArrayBuffer).

Use cases: Image/video processing, data parsing, crypto, ML inference, large sort/filter operations.

💡 Use the Comlink library to make Worker APIs feel like regular async function calls — wraps postMessage/onmessage into an async function interface.

More Browser APIs Questions

EasyWhat is the Fetch API and how do you handle errors correctly?EasyWhat is the difference between localStorage, sessionStorage, and cookies?MediumWhat are Service Workers and what problems do they solve?MediumWhat is the Same-Origin Policy and how does CORS work?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint