Skip to content
Kuza Ndoto Academy

Callbacks & the Event Loop

Beginner → IntermediateChapter 5 · Page 22 of 325 min readUpdated 15 Nov 2026

JavaScript runs your code on a single thread: it can only do one thing at a time. Yet web pages wait for timers, clicks and network replies without freezing. The secret is callbacks plus the event loop, the system that decides when each waiting piece of code gets its turn. Understanding it explains why code doesn't always run in the order it is written.

Callbacks

A callback is a function you pass to another function so it can be called later. Some callbacks run immediately, as part of the call:

const prices = [20, 50, 10];
prices.forEach((price) => console.log(price * 2));   // synchronous callback
console.log("finished");
40 100 20 finished

Others are asynchronous: they run at some point in the future, after something has happened. setTimeout(callback, ms) asks the browser to run a function after at least ms milliseconds, and addEventListener runs one whenever an event fires.

console.log("1. Order placed");
setTimeout(() => console.log("3. Chapati is ready"), 2000);
console.log("2. Waiting at the counter...");
1. Order placed 2. Waiting at the counter... 3. Chapati is ready

The third line appears two seconds later. JavaScript didn't stop and wait; it handed the timer to the browser, carried on with the next line, and ran the callback when the time was up. Even setTimeout(fn, 0) runs after the current code finishes, as you will see below.

The pieces of the event loop

  • Call stack: where JavaScript runs functions, one at a time. When a function is called it goes on top; when it returns it comes off.
  • Web APIs: features the browser provides outside JavaScript, such as timers, fetch and DOM events. They do the waiting.
  • Task queue (also called the macrotask or callback queue): callbacks from timers and events wait here once they are ready.
  • Microtask queue: a higher-priority queue for promise callbacks (.then, .catch, code after await) and queueMicrotask().
  • Event loop: a loop that repeats forever. Whenever the call stack is empty, it runs every microtask in the queue, then takes one task from the task queue, and goes round again (the browser can also repaint the screen between tasks).
Call stack console.log("E") main script Web APIs (the browser does the waiting) setTimeout fetch DOM events Microtask queue: promise callbacks log C log D Task queue: timers, events log B hand off ready 1st 2nd Event loop: when the stack is empty, run every microtask, then the next task
Figure 1. A snapshot while the last line of the example below is running. Waiting happens in the browser; finished callbacks queue up; microtasks always jump ahead of tasks.

Predicting the order

Trace this example with the figure in mind:

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
queueMicrotask(() => console.log("D"));
console.log("E");
A E C D B
  1. A logs straight away (synchronous code on the stack).
  2. setTimeout hands its callback to the browser's timer. After 0 ms it moves to the task queue.
  3. The promise is already resolved, so its .then callback goes to the microtask queue, followed by the queueMicrotask callback.
  4. E logs. The script ends and the stack is empty.
  5. The event loop empties the microtask queue first: C, then D. Only then does it take the timer task: B.

Microtasks can even schedule more microtasks, and they all run before the next task. Here is a slightly harder one:

setTimeout(() => console.log("timeout 1"), 0);

Promise.resolve()
  .then(() => {
    console.log("promise 1");
    setTimeout(() => console.log("timeout 2"), 0);
  })
  .then(() => console.log("promise 2"));

console.log("sync");
sync promise 1 promise 2 timeout 1 timeout 2

When the first .then callback finishes, the second one is queued as a new microtask and runs immediately after, still ahead of both timers. The timers then run in the order they were scheduled.

Don't block the stack

While the call stack is busy, nothing else can happen: no clicks, no timers, no repainting. A long loop freezes the page.

const start = Date.now();
setTimeout(() => console.log("Timer fired after", Date.now() - start, "ms"), 100);

while (Date.now() - start < 1000) {
  // busy for one whole second
}
Timer fired after 1000 ms

The timer asked for 100 ms but had to wait until the loop released the stack (your number may be a few milliseconds higher). The delay you give setTimeout is a minimum, not a promise of exact timing.

Callback hell

When one asynchronous step depends on another, callbacks get nested inside callbacks:

setTimeout(() => {
  console.log("Boil water");
  setTimeout(() => {
    console.log("Add tea leaves");
    setTimeout(() => {
      console.log("Add milk and sugar");
    }, 1000);
  }, 1000);
}, 1000);
Boil water Add tea leaves Add milk and sugar

This "pyramid of doom" becomes hard to read and even harder to add error handling to. Promises and async/await were created to flatten it.

Common mistake

Writing setTimeout(showMessage(), 2000). The brackets call showMessage immediately and pass its return value to setTimeout, so there is no delay. Pass the function itself: setTimeout(showMessage, 2000) or setTimeout(() => showMessage("Karibu"), 2000).

Key points

  • A callback is a function passed to be called later; asynchronous callbacks run after the current code finishes.
  • The browser's Web APIs do the waiting; ready callbacks wait in queues for an empty call stack.
  • The event loop runs all microtasks (promise callbacks) before the next task (timers, events), so promises beat setTimeout(fn, 0).
  • Long-running code blocks everything, and setTimeout delays are minimums.
Up next · Asynchronous JavaScriptPromisesRepresent future values with then and catch.
→

Tip: use the ← and → keys to move between pages.