⚡IntermediateAsync JavaScript

Callbacks & the Event Loop

How JavaScript handles asynchronous operations using callbacks and its single-threaded event loop.

Overview

JavaScript is single-threaded it can only execute one piece of code at a time. Yet it handles many things that take time: network requests, timers, file reads, user input. The mechanism that makes this possible without freezing the program is the event loop. When you call setTimeout, fetch, or attach an event listener, JavaScript hands that work off to the browser (or Node.js) runtime. The runtime handles it in the background and, when the result is ready, places a callback function into the task queue. The event loop continuously checks: "Is the call stack empty? If yes, take the next task from the queue and push it onto the stack." A callback is simply a function passed as an argument to another function, to be called later. Callbacks were JavaScript's original solution to async programming. They work, but deeply nested callbacks "callback hell" led to Promises and async/await, which are built on the same event loop underneath.

Key Points

  • •JavaScript is single-threaded: only one function runs at a time on the call stack
  • •The event loop monitors the call stack and task queue, moving tasks when the stack is empty
  • •Web APIs (setTimeout, fetch, DOM events) run outside the JS thread and push callbacks to the queue when done
  • •A callback is a function passed to another function to be invoked later
  • •Microtask queue (Promises) is processed before the macrotask queue (setTimeout, setInterval)
  • •setTimeout(fn, 0) does not run immediately it queues after the current stack finishes
  • •"Callback hell" refers to deeply nested callbacks that become hard to read and maintain
  • •Understanding the event loop explains why long synchronous loops block the UI

Examples

Basic callback with setTimeout

console.log("Start");

setTimeout(function() {
  console.log("Inside timeout");
}, 1000);

console.log("End");

// Output order:
// Start
// End
// Inside timeout  (after ~1 second)

Even setTimeout(fn, 0) logs after "End" the callback always goes through the queue.

Callback-based async pattern simulating an API call

function fetchUser(id, callback) {
  // Simulate network delay
  setTimeout(function() {
    const user = { id: id, name: "Alice", role: "admin" };
    callback(null, user);  // Node.js convention: error first
  }, 500);
}

fetchUser(1, function(err, user) {
  if (err) {
    console.error("Error:", err);
    return;
  }
  console.log("Got user:", user.name);
});

console.log("fetchUser called waiting...");

The "error-first" callback pattern (err, result) is a Node.js convention used widely in older APIs.

Callback hell and how it grows

// Deeply nested callbacks become hard to follow
getUser(1, function(err, user) {
  if (err) return handleError(err);

  getOrders(user.id, function(err, orders) {
    if (err) return handleError(err);

    getOrderDetails(orders[0].id, function(err, details) {
      if (err) return handleError(err);

      console.log("Details:", details);
      // Each new step adds another level of indentation
    });
  });
});

// Promises and async/await flatten this structure see JS102 and JS103

Common Mistakes

  • Expecting setTimeout(fn, 0) to run synchronously it always runs after the current call stack clears
  • Forgetting error handling in callbacks if you skip the err check your code silently fails
  • Mutating shared state inside callbacks without considering out-of-order execution
  • Assuming callbacks run in the order they were registered when timers have the same delay

Note

Open the browser console and run: console.log(1); setTimeout(() => console.log(2), 0); console.log(3); you will see 1, 3, 2. This is the event loop in action and is one of the most important things to internalize about JavaScript.

Exercises

Write JavaScript code to solve each exercise. Run it and check your output.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What is the event loop's primary job?