Skip to content

Latest commit

 

History

History
41 lines (26 loc) · 1.28 KB

README.md

File metadata and controls

41 lines (26 loc) · 1.28 KB

59. Workers and concurrency

Move CPU-heavy work away from the main thread.

Learn

  • Worker
  • postMessage
  • structured clone
  • termination

How it works

A Web Worker runs JavaScript on a separate thread and communicates by messages. It cannot directly manipulate the page DOM. Send work and results as data, terminate workers when no longer needed, and measure whether the transfer cost is worthwhile. For tiny work, staying on the main thread can be simpler.

Common mistake

Moving a task to a worker does not make an inefficient algorithm efficient; it mainly protects responsiveness.

Guided challenge

Run a CPU-heavy calculation in a worker and compare page responsiveness.

Run the example

Open example.html in a browser and edit example.js. Save, refresh, and use the Console and debugger to inspect values.

Completion check

  • Explain the core idea in your own words without reading the code.
  • Change one input and predict the output before running it.
  • Test one boundary or failure case, then record what you changed.

Local server

Run python3 -m http.server 8000 from the JavaScripts folder, then open this lesson through http://localhost:8000/. Fetch, modules, storage, history, and workers can behave differently or fail under file URLs.