Callbacks & the Event Loop
Trace how JavaScript schedules timers, callbacks, and promise reactions so you can predict the order of asynchronous output.
By the end, you’ll be able to…
- Distinguish synchronous execution from work that is scheduled for later.
- Explain the roles of the call stack, task queue, and microtask queue.
- Predict the output order of timers, promise reactions, and ordinary statements.
01JavaScript runs one step at a time
JavaScript executes your code on a single call stack. Each function call pushes a frame, the function runs to completion, and the frame is popped. Nothing else on that thread — event handlers, timers, rendering — can proceed while a frame is still running. This is synchronous execution: one instruction after another, in the order written.
A loop that checks the clock for 300 milliseconds looks harmless, but it keeps the stack busy for the entire wait. Clicks queue up, animations freeze, and the browser cannot paint. The lesson is not that loops are bad; it is that waiting must be handed off to the host rather than performed by spinning. Asynchronous APIs let the runtime do the waiting while your stack becomes free.
02Timers schedule work; callbacks run later
setTimeout does not pause the program. It asks the host to run a callback after at least the given delay, then returns a timer identifier immediately. The rest of the file continues. Even a delay of zero means later, never now, because the callback must wait for the current stack to empty.
Callbacks are simply functions passed to another function to be invoked later. That inversion is useful, but it splits one logical operation across time. Read the example from top to bottom and predict the order before running it. The synchronous logs finish first; the timer callback is last, after the stack clears.
03The call stack, tasks, and microtasks
The event loop repeatedly checks whether the call stack is empty. When it is, the loop drains all microtasks — promise reactions and queueMicrotask callbacks — then takes one macrotask such as a timer or message event, runs it, and drains microtasks again. Rendering happens between tasks, not in the middle of one.
Microtasks have priority because they run before the next macrotask, and new microtasks queue behind the ones already waiting. In the example, the two synchronous logs run first, then the promise reaction, then the explicitly queued microtask, and finally the timer. Being able to predict that order is the difference between guessing and debugging.
Timers are not precise guarantees of time. A 50ms timer means the callback becomes eligible after 50ms; it still waits for the current task and any microtasks ahead of it. A busy loop or a long render can push the actual run time much later. Treat delays as minimums, and never use a timer to coordinate ordering that promises already express.
04Callback hell and why the shape matters
Node-style callbacks pass an error as the first argument and a result as the second. Every step must check that error before continuing, and dependent work nests inside the previous callback. Three steps produce a pyramid; five steps become hard to read, hard to test, and easy to break when one branch forgets to return.
Callback hell is not only a formatting problem. Control and error handling are scattered across nested functions, and a callback may run zero, one, or many times depending on the API. Promises address this by representing the whole operation as one value with a single settled outcome, which the next lesson explores.
The ideas worth keeping.
- Synchronous code occupies the only call stack; asynchronous APIs hand waiting to the host.
- Microtasks such as promise reactions run before the next macrotask such as a timer.
- Callbacks work but nest poorly; promises represent one future outcome as a value.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Predict the order
Before running the program, write the order of its four messages. Then run it and compare. Adjust the program by adding a second setTimeout with a 10ms delay and predict where it appears.
Explore a worked solution
console.log("script start");setTimeout(() => console.log("timeout"), 0);Promise.resolve().then(() => console.log("promise"));console.log("script end");The synchronous logs run first in source order. The promise reaction is a microtask, so it runs before the timer macrotask. The output is script start, script end, promise, timeout; an additional 10ms timer would still run after the 0ms timer.
Exercise 2: Wrap a callback in a promise
Convert the callback-based loadUser function into a function that returns a promise, then consume the user with then and handle a missing user with catch.
Explore a worked solution
function loadUser(id) { return new Promise((resolve, reject) => { setTimeout(() => { if (id === 1) resolve({ id, name: "Ada" }); else reject(new Error("User not found")); }, 50); });}loadUser(1) .then((user) => console.log(user.name)) .catch((error) => console.error(error.message));The executor calls resolve with the value that used to be passed to the callback. Returning that promise makes the asynchronous result a first-class value, and the catch handles the rejection produced for any other id. The output is Ada.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Predict the order
Before running the program, write the order of its four messages. Then run it and compare. Adjust the program by adding a second setTimeout with a 10ms delay and predict where it appears.
script start script end
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.