JavaScript theorytheory 0/50 · 0%
Browser · hard

43. Web Workers

Getting heavy work off the main thread.

A worker runs a script on its own thread and communicates by structured-clone messages. It has no DOM access, which is exactly why it never blocks rendering.

const w = new Worker("/hash-worker.js");
w.postMessage({ data });
w.onmessage = (e) => setResult(e.data);

This Code Lab runs your JavaScript inside a worker for that reason: an infinite loop can be terminated without freezing the page.

Check your understanding

  1. 1. What can a worker not touch?

  2. 2. How is data passed?

  3. 3. Why run untrusted code in a worker?