SyntaxStudy
Sign Up
HTML Advanced 5 min read

Web Workers

Web Workers

Web Workers run JavaScript in a background thread, keeping the main thread responsive during CPU-intensive tasks.

Example
// main.js
const worker = new Worker("worker.js");
worker.postMessage({ data: largeArray });
worker.onmessage = e => console.log("Result:", e.data);
worker.onerror   = e => console.error(e);

// worker.js
self.onmessage = function(e) {
  const result = e.data.data.reduce((sum, n) => sum + n, 0);
  self.postMessage(result);
};
Pro Tip

Workers cannot access the DOM — they communicate only via postMessage/onmessage.