Manuals / JavaScript / Chapter 11

E · Deep JS · advanced · Week 8–9 · Chapter 11 of 14

Event loop, closures & this

The event loop processes call stack, microtasks (Promises), and macrotasks (setTimeout) in a specific order — interview gold. Closures capture outer variables. this binding depends on call site (arrow functions inherit lexical this). These models explain flaky tests and framework behavior.

Path progress
73%

Step 1 of 5

Event loop order

Run sync code first. Drain all microtasks (Promise callbacks). Then one macrotask (setTimeout). Repeat. That is why Promise.then runs before setTimeout(0).

Event loop orderDrag stickies · tap for tips
Study mapDrag stickies · tap for tipsKeep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Assert the UIdrag · tap →Retry wiselydrag · tap →Seed datadrag · tap →Close the loopdrag · tap →Keep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Pathwise hackdrag · tap →Event loop orderdrag · tap →Try thisdrag · tap →Follow the dashed drag · tap →

Example

console.log("1 sync")
setTimeout(() => console.log("2 macrotask"), 0)
Promise.resolve().then(() => console.log("3 microtask"))
console.log("4 sync")
// Output: 1, 4, 3, 2

Do this now

Predict output, then run: console.log(1); setTimeout(()=>console.log(2)); Promise.resolve().then(()=>console.log(3)); console.log(4).

Was this step clear?
Chapter learning outcomes
  • Call stack & task queues
  • Microtasks vs macrotasks
  • Closures in practice
  • this binding rules
  • Common interview snippets
Chapter videos

JSConf / Philip Roberts

What the heck is the event loop?

Why your awaits (and flaky waits) behave that way.

Open on YouTube →

Clear these before you leave

Side quest

Event loop quiz

Create 5 code snippets with mixed sync/async. Quiz a friend or future self. Answer key in comments.