Callback Execution Context
You'll learn: Where and when a callback function actually runs in JavaScript's execution model.
The Core Idea
When you pass a callback to an asynchronous function, it doesn't execute immediately in your current code flow. Instead, it gets scheduled to run later. Understanding where that callback runs is crucial for debugging async behavior.
Here's the key distinction:
- Synchronous callbacks run immediately on the call stack, right where they're invoked
- Asynchronous callbacks are placed in a queue (task or microtask) and run when the event loop brings them back to the call stack
The Journey of an Async Callback
Think of it like mailing a letter with a return address. When you call setTimeout(callback, 1000):
- Your callback is "registered" but doesn't run yet
- The current function finishes and pops off the call stack
- After 1000ms, your callback is placed in the task queue
- When the call stack is empty, the event loop moves your callback from the queue onto the call stack
- Only then does it execute
Your callback doesn't run "in the background" — it waits its turn and executes on the main thread, just like everything else. The difference is the timing and the path it takes to get there.
Why This Matters
If you console.log inside a callback and wonder why it appears "after" code that was written below it, it's because that callback traveled through a queue first. The call stack had to empty before the event loop could retrieve it.
Key Takeaway: Asynchronous callbacks don't run where they're defined — they're queued and later placed back onto the call stack by the event loop when the stack is clear.