Async JavaScript and the event loop

5 concepts · 10 practice questions

The event loop

The page's JavaScript runs on one main thread that also handles input, style, layout and paint. The event loop takes one task at a time (a script, a click handler, a timer callback) and runs it to completion; nothing interrupts it. Between tasks the browser may render. A long task therefore freezes the page: no clicks, no scrolling feedback, no paint. Keep tasks short, split heavy work into chunks that yield back to the loop, or move it to a Web Worker.

button.addEventListener("click", async () => {
  for (const chunk of chunks(items, 200)) {
    process(chunk);
    // yield so the browser can paint and handle input between chunks
    await new Promise((r) => setTimeout(r, 0));
  }
});

Also covered

Microtasks and macrotasks
Promises and combinators
async/await and error handling
Cancellation and race conditions

Sign in to read the rest and take the 10-question test.

Sign in to continue