Skip to content

Lesson 25 of 50Async JavaScript

The Event Loop

Explain how single-threaded JavaScript handles timers and promises, and predict the exact order async code logs in.

15 min read0/5 questions

Your to-do app reacted to clicks and saved to storage, and every step finished instantly. Real apps also wait: for the network, for timers, for files. JavaScript runs your code on one thread, yet a browser tab stays responsive while it waits for network calls, and a single Node process serves thousands of requests at once. The event loop is how. It also decides the order in which callbacks run, which is why "what does this print?" event loop puzzles are among the most common JavaScript interview questions.

One thread, one call stack

A thread is one sequence of instructions running on the CPU. Your JavaScript runs on a single thread, so only one piece of your code executes at any moment.

The engine tracks what is running with the call stack. Calling a function pushes a frame onto the stack; returning pops it off. When the stack is empty, your code is idle.

JavaScript
function c() { console.log("in c: stack is main > a > b > c");}function b() { c();}function a() { b();}a();console.log("back at the top: stack is just main");
Output
Press Run (⌘ Enter) to see what happens.

Because there is one stack, a slow synchronous task blocks everything. While a loop crunches numbers for two seconds, a browser cannot respond to clicks or repaint, and a Node server cannot answer any other request.

JavaScript
const start = Date.now();while (Date.now() - start < 300) { // busy-wait for 300 ms: nothing else can run during this loop}console.log(`blocked for ${Date.now() - start} ms`);
Output
Press Run (⌘ Enter) to see what happens.

Handing work to the host

So how does waiting work? The engine does not wait. When you call setTimeout, fetch or Node's fs.readFile, you hand the job to the host (the browser's Web APIs or Node's libuv library), which runs it outside your JavaScript thread. Your code keeps going immediately.

When the host finishes (the timer expires, the response arrives), it puts your callback into a queue. The event loop is a simple rule that runs forever:

  1. Run the current task until the call stack is empty (run to completion: a task is never interrupted halfway).
  2. Run every job in the microtask queue, including any new ones added while doing so.
  3. Let the browser render if it needs to.
  4. Take the next one task from the task queue (also called the macrotask queue) and go back to step 1.

Two queues, two priorities:

QueueWhat goes in itPriority
Microtask queuePromise callbacks (then, catch, finally, code after await), queueMicrotaskDrained completely after each task
Task queuesetTimeout, setInterval, I/O callbacks, UI events, messagesOne per loop turn
Quick check
A setTimeout(fn, 0) is scheduled, then the code runs a loop that takes 500 ms. When does fn run?
Need a nudge? A hint rules out a wrong answer.

The classic example

Here is the program every interviewer loves. Step through it and watch the four areas.

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
queueMicrotask(() => console.log("D"));
console.log("E");
Sync, timer, promise, microtask

Call stack

  • main
  • log("A")

Web APIs / timers

    Microtasks

      Task queue

        Console

        A

        The script itself is the first task. console.log("A") runs immediately.

        1/9

        That is why setTimeout(fn, 0) always runs after already-resolved promises: promise callbacks are microtasks, and all microtasks run before the next task. Run it yourself:

        JavaScript
        console.log("A");setTimeout(() => console.log("B"), 0);Promise.resolve().then(() => console.log("C"));queueMicrotask(() => console.log("D"));console.log("E"); // Keep the program alive until the timer fires (the runner stops when your code ends)await new Promise((resolve) => setTimeout(resolve, 20));
        Output
        Press Run (⌘ Enter) to see what happens.
        Predict the outputJavaScript

        What does this print?

        setTimeout(() => console.log(1), 0);
        Promise.resolve().then(() => console.log(2));
        console.log(3);
        Need a nudge? Hints walk you through it.

        Microtasks that schedule microtasks

        Because the loop drains the microtask queue completely, a microtask that queues another microtask runs it before any timer gets a turn. Timers created in a microtask go to the back of the task queue.

        Predict the outputJavaScript

        What does this print?

        setTimeout(() => console.log("timeout"), 0);
        Promise.resolve()
        .then(() => {
          console.log("then 1");
          setTimeout(() => console.log("inner timeout"), 0);
        })
        .then(() => console.log("then 2"));
        console.log("sync");
        Need a nudge? Hints walk you through it.

        The flip side is starvation: a microtask that keeps scheduling microtasks forever never lets a task run, so timers, clicks and rendering all freeze. A setTimeout loop does not have this problem, because each turn yields back to the loop.

        Put it in order4 steps

        Order one turn of the event loop.

        1. Tap the steps below in the right order.
        Need a nudge? A hint shows where it starts.

        Why this design

        The alternative to an event loop is threads: give each request or each slow call its own thread that sits and waits. Threads use memory (often around 1 MB of stack each), and sharing data between them needs locks, which cause deadlocks and race conditions.

        JavaScript instead has one thread that never waits. While a request waits on the database, the thread handles other requests' callbacks. Because a task runs to completion, two pieces of your code never run at the same time, so you never need locks. The cost is that you must never block the thread with long synchronous work. For CPU-heavy jobs, use a Web Worker in the browser or a worker thread in Node, each with its own thread and its own event loop. (The runnable blocks in this course run inside a Web Worker for exactly this reason.)

        Quick check
        A Node API resizes uploaded images with pure JavaScript, and the server stops responding to other requests during each resize. Why?
        Need a nudge? A hint rules out a wrong answer.

        Node's loop, briefly

        Node's event loop (provided by libuv) has the same idea with more structure. Each turn moves through phases: timers (setTimeout, setInterval), poll (most I/O callbacks: network, files), check (setImmediate), and close callbacks. Between every individual callback, Node drains two queues: process.nextTick callbacks first, then promise microtasks.

        You rarely need the phase details, but two facts come up: process.nextTick runs before promise callbacks, and setImmediate runs in the check phase right after I/O. In browsers, rendering and requestAnimationFrame sit between tasks instead.

        ChallengeEasy

        defer

        Write defer(fn). It must not call fn right away. Instead it schedules fn to run as a microtask: after the current synchronous code finishes, but before any setTimeout callbacks. It returns a promise that resolves with fn's return value, or rejects if fn throws.

        setTimeout(() => console.log("timer"), 0);
        defer(() => console.log("deferred"));
        console.log("sync");
        // sync
        // deferred
        // timer
        JavaScript
        function defer(fn) { // Schedule fn as a microtask and return a promise of its result. return Promise.resolve();}
        ChallengeMedium

        debounce

        Write debounce(fn, ms). It returns a function that, when called, waits ms milliseconds before calling fn. If it is called again during the wait, the timer restarts. When fn finally runs, it receives the arguments of the most recent call.

        This is how search boxes avoid sending a request on every keystroke: only after the user pauses.

        const search = debounce((q) => console.log("search", q), 300);
        search("r"); search("re"); search("react");
        // ...300 ms of quiet...
        // search react
        JavaScript
        function debounce(fn, ms) { // Keep the pending timer in a closure; clear it on every call. return (...args) => {};}
        Key terms
        call stack
        The stack of function frames currently running. JavaScript has one, so one thing runs at a time.
        event loop
        The loop that runs a task, drains all microtasks, renders, then takes the next task.
        task queue
        Also called the macrotask queue. Holds callbacks from timers, I/O and events; one runs per loop turn.
        microtask queue
        Holds promise callbacks and queueMicrotask jobs. Fully drained after every task, before timers.
        run to completion
        Once a task starts, it runs until the stack is empty. Nothing interrupts it.
        libuv
        The C library that gives Node its event loop, thread pool and non-blocking I/O.