On this page
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
- > Execution Order Example
- > Async Iterators (`for await...of`)
Call Stack, Microtasks & Macrotasks
JavaScript executes on a single main thread governed by the Event Loop:
- Run the current task (macrotask) to completion on the call stack (initial script, timer callback, DOM event, network callback).
- Drain the entire microtask queue (
Promise.then/.catch/.finally,queueMicrotask,MutationObserver) — including any new microtasks queued while draining. - If in a browser and a frame is due, run
requestAnimationFramecallbacks and render (Style -> Layout -> Paint). - 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
- tuts/javascript/builtins/promise_and_async
- tuts/javascript/tutorials
- tuts/javascript/tutorials/event_loop_and_async_programming
- tuts/javascript/tutorials/iterators_and_generators
- tuts/javascript/tutorials/modules_and_error_handling
- tuts/javascript/tutorials/prototype_chain_and_new_flow
- tuts/programming/concurrency
- tuts/programming/concurrency/concurrency_vs_parallelism
- tuts/programming/paradigms/declarative_and_event_driven
- tuts/web/apis/observers_and_workers
- tuts/web/rendering
Related notes
- tuts/javascript/builtins/promise_and_async Linked here; links to this page; shared tags: #async, #javascript, #web
- tuts/javascript/tutorials Linked here; links to this page; shared tags: #javascript, #tutorials, #web
- tuts/javascript/tutorials/modules_and_error_handling Linked here; links to this page; shared tags: #javascript, #tutorials, #web
- tuts/javascript/tutorials/prototype_chain_and_new_flow Linked here; links to this page; shared tags: #javascript, #tutorials, #web
- tuts/javascript/tutorials/iterators_and_generators links to this page; shared tags: #javascript, #tutorials, #web
- tuts/web/apis/fetch_and_networking Linked here; shared tags: #web
- tuts/web/apis/observers_and_workers links to this page; shared tags: #web
- tuts/web/rendering links to this page; shared tags: #web
- tuts/web/rendering/reflow_repaint_and_performance Linked here; shared tags: #web
- tuts/programming/concurrency links to this page