Chapter 36 of 49

Asynchronous JavaScript & the Event Loop

Imagine you walk into a tea stall and order a cup of chai. The shopkeeper could do two things:

  • Stand still and stare at the pot until your chai is ready, ignoring every other customer. (Slow and frustrating.)

  • Put the pot on the stove, take the next customer's order, and hand you your chai when it's ready. (Much better.)

JavaScript works like the second shopkeeper. Many operations, such as waiting for a timer, downloading data from a server, or reading a file, take time. Instead of freezing while it waits, JavaScript starts the operation, keeps running other code, and comes back to handle the result later.

This is called asynchronous programming, and the mechanism that makes it work is the event loop. This chapter explains how it works, so that the next chapters on promises, async/await, and fetch() make complete sense.


Synchronous Code

Everything we've written so far has been synchronous: one line runs, finishes, and then the next line runs.

console.log("Step 1");
console.log("Step 2");
console.log("Step 3");

Output:

Step 1
Step 2
Step 3

Synchronous code runs line by line, in order. Each line must finish before the next one starts.

That's simple and predictable. The problem appears when one line takes a long time.


The Problem: Blocking

JavaScript is single-threaded. It has one main thread, which means it can only do one thing at a time.

If a piece of code takes a long time, everything else has to wait:

console.log("Start");

// Simulate a slow task that keeps JavaScript busy for 3 seconds
const end = Date.now() + 3000;
while (Date.now() < end) {
    // doing nothing, just wasting time
}

console.log("End");

Output:

Start
End

"End" only appears after 3 seconds. In a browser, the whole page would freeze during those 3 seconds: buttons stop responding, scrolling stops, and nothing updates. This is called blocking the main thread.

Now imagine if every network request worked like this. A page that loads data from a slow server would be frozen until the data arrived. That's why JavaScript needs asynchronous operations.


Asynchronous Code with setTimeout()

Asynchronous code starts a task now and handles its result later, without stopping the rest of the program from running in the meantime.

The simplest asynchronous function is setTimeout(). It runs a callback function after a delay (in milliseconds):

setTimeout(callback, delayInMilliseconds);

Let's see what order things happen in:

console.log("Start");

setTimeout(() => {
    console.log("Timer finished");
}, 2000);

console.log("End");

Output:

Start
End
Timer finished

JavaScript didn't wait for 2 seconds at the setTimeout() line. It scheduled the callback, moved on immediately, printed "End", and about 2 seconds later ran the callback.

Here's the surprising part. What if the delay is 0?

console.log("Start");

setTimeout(() => {
    console.log("Timeout with 0 ms");
}, 0);

console.log("End");

Output:

Start
End
Timeout with 0 ms

Even with a 0 ms delay, the callback runs after "End". To understand why, we need to look at how JavaScript runs code behind the scenes.


The Pieces: Call Stack, Web APIs, Queue, and Event Loop

The JavaScript engine itself (like V8 in Chrome and Node.js) only knows how to run code. Timers, network requests, and DOM events are provided by the environment it runs in: the browser or Node.js. Four pieces work together:

1. The Call Stack

The call stack keeps track of which function is currently running. When a function is called, it is pushed onto the stack. When it returns, it is popped off.

function greet() {
    console.log("Hello");
}

function start() {
    greet();
    console.log("Done");
}

start();

Output:

Hello
Done
What happens                     Call stack (bottom → top)
start() is called                [start]
start() calls greet()            [start, greet]
greet() calls console.log        [start, greet, console.log]   prints "Hello"
console.log returns              [start, greet]
greet() returns                  [start]
start() calls console.log        [start, console.log]          prints "Done"
console.log returns              [start]
start() returns                  []   (empty)

JavaScript can only run whatever is on top of the stack. While the stack is busy, nothing else can run.

2. Web APIs (the Environment)

When you call setTimeout(), the browser (or Node.js) starts the timer, not the JavaScript engine. The engine hands the job over and carries on. The same happens for network requests and event listeners. In Node.js, the equivalent work is handled by its own system (a C library called libuv), but the idea is the same.

3. The Task Queue

When a timer finishes (or a click happens, or data arrives), its callback isn't run immediately. It is placed in a waiting line called the task queue (also called the callback queue or macrotask queue).

4. The Event Loop

The event loop is a process that keeps checking: "Is the call stack empty? If yes, take the next callback from the queue and push it onto the stack."

Put together:

   ┌──────────────┐        hands off         ┌──────────────────┐
   │  Call Stack  │ ───────────────────────► │ Web APIs / Node  │
   │ (runs code)  │   setTimeout, fetch...   │ (timers, network)│
   └──────▲───────┘                          └────────┬─────────┘
          │                                           │ when done, callback
          │ event loop moves a callback               ▼ is queued
          │ only when the stack is EMPTY     ┌──────────────────┐
          └───────────────────────────────── │    Task Queue    │
                                             └──────────────────┘

Tracing an Example Step by Step

Let's trace the setTimeout(..., 0) example again:

console.log("Start");

setTimeout(() => {
    console.log("Timeout");
}, 0);

console.log("End");
1. console.log("Start") goes on the stack, prints "Start", pops off.
2. setTimeout(...) goes on the stack. The environment starts a 0 ms timer
   and keeps the callback. setTimeout pops off immediately.
3. The timer finishes almost instantly, so the callback is put in the task queue.
   But the stack is NOT empty yet: the rest of the script is still running.
4. console.log("End") runs and prints "End".
5. The script finishes. The call stack is now empty.
6. The event loop sees an empty stack, takes the callback from the queue,
   and runs it. It prints "Timeout".

Output:

Start
End
Timeout

So the delay in setTimeout() is a minimum waiting time, not a guarantee. The callback runs only when the delay has passed and the call stack is empty.

A Blocked Timer

This also means slow synchronous code delays timers:

const startTime = Date.now();

setTimeout(() => {
    console.log("Timer ran after at least 2 seconds");
    console.log("Waited 2s or more?", Date.now() - startTime >= 2000);
}, 100);

// Block the main thread for 2 seconds
while (Date.now() - startTime < 2000) {}

console.log("Blocking code finished");

Output:

Blocking code finished
Timer ran after at least 2 seconds
Waited 2s or more? true

The timer was due after 100 ms, but the callback had to wait until the stack was free, about 2 seconds later. Lesson: never run long, heavy loops on the main thread in an app that needs to stay responsive.


The Microtask Queue

There's actually a second queue with a higher priority: the microtask queue.

Callbacks from promises (which we'll study in the next chapter) go into the microtask queue. You can also add one directly using queueMicrotask().

The rule is:

After the current script (or task) finishes, the event loop runs ALL microtasks in the microtask queue before it takes the next task from the task queue.

console.log("1: script start");

setTimeout(() => {
    console.log("4: setTimeout (task)");
}, 0);

Promise.resolve().then(() => {
    console.log("3: promise callback (microtask)");
});

console.log("2: script end");

Output:

1: script start
2: script end
3: promise callback (microtask)
4: setTimeout (task)

Even though the setTimeout() was scheduled first, the promise callback ran first, because microtasks have priority over tasks.

You don't need to understand Promise.resolve().then(...) yet. For now, just know that it schedules a microtask.

The Event Loop Algorithm

Here's a simplified version of what the event loop does, over and over:

1. Run the current task (at the start, this is your whole script)
   until the call stack is empty.
2. Run every microtask in the microtask queue.
   (If a microtask adds more microtasks, run those too, until the queue is empty.)
3. In a browser: update the screen (re-render) if needed.
4. Take the NEXT task from the task queue and go back to step 1.

Task queue (macrotasks)

Microtask queue

setTimeout, setInterval callbacks

Promise .then() / .catch() / .finally() callbacks

DOM events like clicks and key presses

Code after await (covered later)

Network and I/O callbacks

queueMicrotask() callbacks

One task per loop turn

All of them, before the next task

A Trickier Example

console.log("A");

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

Promise.resolve().then(() => {
    console.log("C");
    setTimeout(() => console.log("D"), 0);
});

queueMicrotask(() => console.log("E"));

console.log("F");

Output:

A
F
C
E
B
D

Let's trace it:

Script runs:  prints A, queues task B, queues microtask C,
              queues microtask E, prints F.
              Tasks:      [B]
              Microtasks: [C, E]

Microtasks:   run C → prints C, queues task D.   Tasks: [B, D]
              run E → prints E.

Next task:    run B → prints B.
Next task:    run D → prints D.

Questions like this are very popular in JavaScript interviews.


Callbacks: The Original Way to Handle Async Results

Before promises existed, asynchronous results were handled using callbacks (which you met in the callbacks chapter): you pass a function that will be called when the work is done.

function downloadFile(name, callback) {
    console.log(`Downloading ${name}...`);

    setTimeout(() => {
        callback(`${name} contents`);
    }, 1000);
}

downloadFile("notes.txt", (data) => {
    console.log("Got:", data);
});

console.log("Doing other work meanwhile");

Output:

Downloading notes.txt...
Doing other work meanwhile
Got: notes.txt contents

You Can't Simply return an Async Result

A very common beginner mistake:

function getUser() {
    let user;

    setTimeout(() => {
        user = { name: "Rahul" };
    }, 1000);

    return user;
}

console.log(getUser());

Output:

undefined

getUser() returns immediately, long before the timer callback sets user. The value simply doesn't exist yet. That's why async results must be delivered through a callback (or, as we'll see next, a promise).

Callback Hell

When several async steps depend on each other, callbacks get nested inside callbacks:

function step(name, callback) {
    setTimeout(() => {
        console.log(name);
        callback();
    }, 500);
}

step("1. Log in", () => {
    step("2. Load profile", () => {
        step("3. Load orders", () => {
            step("4. Show dashboard", () => {
                console.log("All done!");
            });
        });
    });
});

Output:

1. Log in
2. Load profile
3. Load orders
4. Show dashboard
All done!

It works, but this ever-growing sideways "pyramid" is known as callback hell. Real code also needs error handling at every level, which makes it much worse:

  • The code is hard to read and change.

  • Errors must be handled separately at every level.

  • A regular try...catch around the outer call can't catch errors thrown inside the callbacks, because by the time they run, the outer code has already finished.

try {
    setTimeout(() => {
        throw new Error("Oops!");
    }, 1000);
} catch (error) {
    console.log("Caught:", error.message); // never runs
}

The try block finishes immediately after scheduling the timer. When the callback throws a second later, the try...catch is long gone, so the error is uncaught. In Node.js, an uncaught error like this crashes the program; in a browser, it shows up as an error in the console.

Promises were added to JavaScript (ES2015) to solve exactly these problems, and async/await (ES2017) made them even easier. That's what the next two chapters are about.


Browser vs Node.js

Both browsers and Node.js use an event loop with tasks and microtasks, so everything in this chapter applies to both. Node.js adds a few extras you may see in backend code:

  • setImmediate(callback) schedules a callback for a later phase of Node's event loop.

  • process.nextTick(callback) runs a callback before promise microtasks.

These are Node-only. In browser code, stick to setTimeout(), promises, and queueMicrotask().


Common Mistakes

  • Thinking setTimeout(fn, 1000) runs exactly after 1 second. It runs no earlier than 1 second, and later if the call stack is busy.

  • Thinking setTimeout(fn, 0) runs immediately. It runs after the current code and all microtasks finish.

  • Trying to return a value from inside an async callback. The outer function has already returned.

  • Thinking JavaScript runs your code in parallel. Your JavaScript runs on one thread. The waiting (timers, network) happens in the environment, in the background.

  • Running heavy loops on the main thread. This freezes the page and delays every timer and event.


Interview Tips

  • "Is JavaScript single-threaded?" Yes, your code runs on a single main thread. Asynchronous behaviour comes from the environment (browser or Node.js) plus the event loop.

  • "What is the event loop?" A loop that waits for the call stack to become empty, then runs all pending microtasks, then moves the next task from the task queue onto the stack.

  • "Microtask vs macrotask?" Promise callbacks and queueMicrotask() are microtasks; setTimeout, events, and I/O callbacks are tasks. All microtasks run before the next task.

  • Output prediction: first print all synchronous logs in order, then microtasks in the order they were queued, then tasks (timers) in order of when they're due.

Conclusion

JavaScript runs on a single thread, but it doesn't have to wait around for slow operations:

Call stack     → runs your code, one function at a time
Web APIs       → the environment handles timers, network, events in the background
Microtask queue→ promise callbacks; all run as soon as the stack is empty
Task queue     → timer and event callbacks; one runs per loop turn
Event loop     → moves callbacks onto the stack when it is empty

Key takeaways:

  • Synchronous code always finishes first.

  • Then all microtasks run.

  • Then tasks such as setTimeout callbacks run, one at a time.

Callbacks were the original way to handle async results, but they lead to deeply nested, hard-to-manage code. In the next chapter, we'll learn about promises, a much cleaner way to work with values that will be available in the future.