← All lessons
How Web Workers work
Hand the work to a second thread
Main thread
Worker
main.js
// on the main thread: the page stops while this runsconst count = countPrimes(5_000_000);render(count); // in a worker: a second thread does itconst worker = new Worker("primes.js");worker.postMessage(5_000_000); // a copyworker.onmessage = (e) => { render(e.data); // back on the main thread}; // transfer: move the memory, don't copy itconst buf = new ArrayBuffer(64 * 1024 * 1024);worker.postMessage(buf, [buf]);buf.byteLength; // 0primes.js
// primes.js: its own thread, no document or windowself.onmessage = (e) => { const count = countPrimes(e.data); self.postMessage(count);};Count primes for real on the main thread or in a worker
app.js
// Main threadbutton.onclick = () => { out.textContent = countPrimes(n);}; // Web Workerconst worker = new Worker( new URL("./worker.js", import.meta.url), { type: "module" },);button.onclick = () => worker.postMessage(n);worker.onmessage = (e) => { out.textContent = e.data;};primes.js
// trial division, slow on purposefunction countPrimes(n) { let count = n > 2 ? 1 : 0; for (let i = 3; i < n; i += 2) { let prime = true; for (let d = 3; d * d <= i; d += 2) { if (i % d === 0) { prime = false; break; } } if (prime) count++; } return count;}Copy or transfer a buffer to the worker and back
postMessage-
byteLength after-
round trip-
got back-
main.js
const buf = new ArrayBuffer(mb * 1024 * 1024); // copy: the worker gets a cloneworker.postMessage({ buf, move: false });buf.byteLength; // still the full size // transfer: the memory moves to the workerworker.postMessage({ buf, move: true }, [buf]);buf.byteLength; // 0, detachedworker.js
// worker.js: send it back the way it cameself.onmessage = (e) => { const { buf, move } = e.data; self.postMessage(buf, move ? [buf] : []);};Topics
Next: How Git works
Open lesson