QA
Intermediate LevelHTML & Semantic Web

How do Web Workers offload heavy computations from the main UI thread?

❓ Interview Prompt: Explain Web Workers API, background thread execution, postMessage communication, and preventing UI freezes.

JavaScript runs on a single main UI thread. Heavy calculations (image processing, big data sorting) block main thread rendering, freezing the UI.

Web Workers:

Web Workers execute JavaScript code in an isolated background thread.

•
Communication occurs via 'postMessage()' and 'onmessage'.
•
Workers do NOT have access to the DOM, 'window', or 'document' objects!

Code Implementation Example

javascript
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ number: 42 });
worker.onmessage = (event) => console.log('Calculation result:', event.data);

// worker.js (Background Thread)
self.onmessage = (event) => {
  const result = heavyCalculation(event.data.number);
  self.postMessage(result);
};
💡Offloading heavy calculations to background Web Worker thread using postMessage.
🎯 Interview Key Takeaway

Use Web Workers to execute heavy CPU computations in background threads, keeping main UI rendering responsive.

#Web Workers#Multithreading#Performance#Intermediate
Back to all HTML & Semantic Web Questions→

More HTML & Semantic Web Interview Questions

Beginner LevelHTML & Semantic Web

What is Semantic HTML and why is it essential for modern web applications?

Beginner LevelHTML & Semantic Web

What is <!DOCTYPE html> and what happens if it is omitted?

Beginner LevelHTML & Semantic Web

What is the difference between inline and block-level HTML elements?