๐Ÿงต Web Workers

True background threads in the browser โ€” run heavy computation without blocking the UI

60
UI FPS
idle
Heavy Task
0ms
Time Elapsed
โ€”
Computation Result
Main Thread (UI) idle
๐ŸŽจ Paint frame
๐Ÿ‘† Handle click event
๐Ÿ”„ Run React render
โณ Waiting for tasks...
Thread ready
Web Worker Thread idle
๐Ÿ“ญ No tasks assigned
Workers run in a separate OS thread.
They cannot touch the DOM directly.
They communicate via postMessage().
Worker standing by

๐Ÿ“จ postMessage() Channel โ€” How Worker & Main Thread Talk

Messages will appear here when simulation runs...
โŒ Without Worker โ€” UI Freezes
// Runs on main thread
function heavyCalc() {
  let result = fibonacci(40);
  // โ†‘ Blocks for ~2s on main thread
  // UI is FROZEN during this time
  // No clicks, no animations ๐Ÿ˜ฑ
  return result;
}
โœ… With Worker โ€” UI Stays Smooth
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ n: 40 });
worker.onmessage = (e) => {
  console.log(e.data.result);
};
// worker.js
onmessage = (e) => {
  postMessage(fib(e.data.n));
};
๐Ÿง  When to use Web Workers: CPU-intensive tasks like image processing, video encoding, data parsing (large JSON/CSV), cryptography, complex physics simulations, and machine learning inference. Rule of thumb: if it takes >16ms to run, it will drop a frame โ€” use a Worker.