HTML5 & Web APIs (50 Qs)•Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)
Web Workers: Offloading CPU-Intensive Tasks from the Main Thread.
senior LevelCode ExampleSystem Design
In Simple Words: JavaScript runs on a single thread. Running a 3-second data encryption or image filtering computation freezes the entire UI, rendering animations choppy and blocking user clicks. Web Workers execute JavaScript on a separate background OS thread:
javascript
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ data: massiveDataset });
worker.onmessage = (e) => {
console.log('Result from worker:', e.data);
};
javascript
// worker.js (Background thread - No access to DOM or window!)
self.onmessage = (e) => {
const result = heavyComputation(e.data);
self.postMessage(result);
};