Web Workers
Web Workers run JavaScript in a background thread, keeping the main thread responsive during CPU-intensive tasks.
Web Workers run JavaScript in a background thread, keeping the main thread responsive during CPU-intensive tasks.
// 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);
};
Workers cannot access the DOM — they communicate only via postMessage/onmessage.