
Async JavaScript Explained: How setTimeout Really Works
console.log(1); setTimeout(() => { console.log(2); }, 0); console.log(3); Output order: First, 1 is printed immediately. Then 3 is printed (because synchronous code runs before the event loop picks up the timeout). Finally, 2 is printed after the current call stack clears, even though the timeout is 0. This demonstrates how JavaScript’s event loop and task queue work. Execution Flow Diagram Call Stack (synchronous execution): console.log(1) → prints 1 setTimeout(...) → schedules callback (console.log(2)) in the Callback Queue console.log(3) → prints 3 Callback Queue (asynchronous tasks): After the stack is clear, the event loop picks up the scheduled callback: console.log(2) → prints 2 Visual Representation Call Stack: Callback Queue: ------------------- ------------------- console.log(1) → 1 setTimeout(...) → (callback stored here) console.log(3) → 3 (Event loop runs → moves callback to stack) console.log(2) → 2 This happens because setTimeout(0) doesn’t mean “immediately” — it means
Continue reading on Dev.to React
Opens in a new tab

