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.
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).
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, 2Do this now
Predict output, then run: console.log(1); setTimeout(()=>console.log(2)); Promise.resolve().then(()=>console.log(3)); console.log(4).
Chapter learning outcomes
- Call stack & task queues
- Microtasks vs macrotasks
- Closures in practice
- this binding rules
- Common interview snippets
Chapter videos
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.