On this page
  1. Event Loop & Async Programming
  2. Contents
  3. Call Stack, Microtasks & Macrotasks
  4. Execution Order Example
  5. Async Iterators (for await...of)

Event Loop & Async Programming

Prev: Prototype Chain & new Instantiation Flow | Up: tutorials | Next: ES Modules & Error Handling
Rel: Promise & Async, Fetch & Networking, Reflow, Repaint & Performance
Ref: MDN Web Docs — The Event Loop
Tags: #public #web #javascript #tutorials #async #event-loop


Contents


Call Stack, Microtasks & Macrotasks

JavaScript executes on a single main thread governed by the Event Loop:

  1. Run the current task (macrotask) to completion on the call stack (initial script, timer callback, DOM event, network callback).
  2. Drain the entire microtask queue (Promise.then/.catch/.finally, queueMicrotask, MutationObserver) — including any new microtasks queued while draining.
  3. If in a browser and a frame is due, run requestAnimationFrame callbacks and render (Style -> Layout -> Paint).
  4. Pick the next macrotask and repeat.

Execution Order Example

console.log("1. sync start");

setTimeout(() => console.log("4. macrotask (timer)"), 0);

Promise.resolve().then(() => console.log("3. microtask (promise)"));

console.log("2. sync end");
// Output: 1 -> 2 -> 3 -> 4

Async Iterators (for await...of)

async function* ticker(count) {
  for (let i = 1; i <= count; i++) {
    await new Promise((r) => setTimeout(r, 10));
    yield i;
  }
}

for await (const n of ticker(3)) {
  console.log(n);
}

Linked from

Related notes