Skip to content
HTML5

Web Workers

Run heavy computation on a background thread.

By EZ4Code Team
web-workersconcurrency

Code

// main.js
const worker = new Worker("worker.js");

worker.postMessage({ cmd: "sum", nums: [1, 2, 3, 4] });

worker.onmessage = e => {
  console.log("Result:", e.data);
};

worker.onerror = e => console.error("Worker error:", e.message);

// worker.js
self.onmessage = function (e) {
  const { cmd, nums } = e.data;
  if (cmd === "sum") {
    const total = nums.reduce((a, b) => a + b, 0);
    self.postMessage(total);
  }
};

// Workers cannot access the DOM, but can use fetch,
// setTimeout, and importScripts("lib.js")

Explanation

Web Workers run scripts on a background thread, keeping heavy computation off the UI thread. The main thread and worker communicate asynchronously via postMessage and onmessage. Workers have no DOM access but can use fetch, timers, and importScripts.

More HTML5 Snippets