freecoding.school100% FREE · NO SIGNUP
Input HarborISSUE #31 of 46

web workers · background threads

FormaVSCaptain Invalid Input
Forma saysWeb Workers run JavaScript on a background thread so heavy work never freezes the page.

JavaScript is single-threaded — a long loop freezes the whole UI. A Web Worker runs a separate script on its own thread. You talk to it with postMessage and listen with onmessage; it can't touch the DOM, only crunch data and message results back.

Use workers for parsing big files, image processing, or any computation that would otherwise janky-up scrolling and clicks. Normally a worker is its own file; you can also build one from a Blob URL for single-file demos.

Power-ups you unlock

Captain Invalid Input attacks — common mistakes

Boss battleSpin up an inline (Blob) worker that sums to 100 million and posts the result back without freezing the button.

Example code

<!doctype html>
<html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:sans-serif;padding:20px">
  <button id="b" style="font:inherit;color:#b388ff;background:none;border:1px solid #b388ff;padding:6px 12px;border-radius:3px">heavy sum (off-thread)</button>
  <pre id="out" style="margin-top:12px"></pre>
  <script>
    const code = 'onmessage=()=>{let s=0;for(let i=0;i<1e8;i++)s+=i;postMessage(s)}';
    const w = new Worker(URL.createObjectURL(new Blob([code],{type:'text/javascript'})));
    w.onmessage = e => document.getElementById('out').textContent = 'sum = ' + e.data;
    document.getElementById('b').onclick = () => { document.getElementById('out').textContent='working…'; w.postMessage(0); };
  </script>
</body></html>
▶ Open the interactive comic issue
‹ Web Storage · LocalStorage · SessionStorageServer-Sent Events · One-Way Push ›