JS
Frontend

JavaScript Event Loop Explained

Mayur Dabhi
Mayur Dabhi
May 12, 2026
14 min read

You add a setTimeout(fn, 0) to "run something right after", and it fires later than a Promise callback you wrote below it. Or a spinner freezes mid-animation while a big JSON payload gets processed. Or a Node.js API gets slow under load even though CPU usage looks fine. All three come down to the same thing: the event loop.

JavaScript runs your code on one thread, one piece at a time. Fetching data, handling clicks and animating the UI all at once only works because the slow parts happen outside that thread and come back as queued callbacks. This post walks through the call stack, Web APIs, the two queues, how async/await fits in, and the mistakes that cause most of the confusing bugs.

One thread, many helpers

Your JavaScript runs on a single thread, but the runtime around it (the browser or Node.js) uses other threads for timers, networking and file I/O. The event loop is what hands results from those threads back to yours.

The JavaScript Runtime Environment

The event loop only makes sense once you know what it's moving things between. In a browser, the runtime has these parts:

JavaScript Engine (V8) Call Stack main() greet() ← LIFO Memory Heap Objects & Variables stored here Web APIs setTimeout fetch / XHR DOM Events rAF / IO Microtask Queue Promise.then · queueMicrotask ← Higher priority Callback Queue setTimeout · setInterval · I/O ← Lower priority (macrotasks) Event Loop calls callback push to call stack

The browser runtime: how the engine, Web APIs, queues and event loop connect

The Call Stack: How JavaScript Executes Code

Every time you call a function, the engine pushes a stack frame that records where to return when it's done. When the function returns, the frame is popped. It's last in, first out, so the function on top is always the one running right now.

Call Stack Visualization
function multiply(a, b) {
    return a * b;
}

function square(n) {
    return multiply(n, n);  // multiply pushed onto stack
}

function printSquare(n) {
    const result = square(n);  // square pushed onto stack
    console.log(result);
}

printSquare(4);  // printSquare pushed onto stack

// Stack progression:
// 1. [printSquare]
// 2. [printSquare, square]
// 3. [printSquare, square, multiply]
// 4. [printSquare, square]   ← multiply returns 16
// 5. [printSquare]           ← square returns 16
// 6. []                      ← printSquare logs 16, returns

While the stack is busy with synchronous code, nothing else runs. That's what "blocking the event loop" means. A long loop or heavy computation on the main thread stops the browser from handling clicks, painting frames or running any callbacks until the stack is empty.

Blocking the Event Loop

Keep CPU-heavy work off the main thread. A while loop that runs for 5 seconds freezes the whole page, and Chrome will eventually show a "Page Unresponsive" dialog. Offload heavy work to Web Workers, or break it into chunks using setTimeout(fn, 0) to yield control back to the event loop between iterations.

Web APIs: Delegating Async Work

When you call setTimeout, fetch, or addEventListener, the browser does the actual waiting on its own threads, outside the JavaScript engine. Your code keeps going on the next line.

Web API Delegation Example
console.log('1: Start');

// setTimeout hands off to the Web API (browser timer)
// JS does NOT pause; it continues immediately
setTimeout(() => {
    console.log('3: Timeout callback (runs after stack clears)');
}, 1000);

// fetch hands off to the Web API (network layer)
fetch('/api/data')
    .then(res => res.json())
    .then(data => {
        console.log('4: Fetch resolved');
    });

console.log('2: End');

// Output order:
// 1: Start
// 2: End
// 3: Timeout callback (runs after stack clears, ~1 second later)
// 4: Fetch resolved (runs after fetch completes, order relative to timeout varies)

setTimeout doesn't pause anything. It tells the browser "queue this callback after at least 1000ms" and returns. When the timer fires, the callback goes into the Callback Queue and waits there until the event loop picks it up.

That "at least" matters more than people expect. Browsers clamp nested timers to a minimum of about 4ms once they're nested five levels deep, and background tabs throttle timers to roughly once per second (sometimes much less often). If a polling loop or countdown behaves strangely only when the tab isn't visible, this is usually why.

How Web APIs Work Internally

1

JS calls setTimeout(fn, 1000)

The JS engine passes the callback and delay to the browser's Web API. The Web API starts an internal timer and immediately returns control to JavaScript.

2

Browser timer runs in the background

The browser's C++ timer runs in a separate system thread. After 1000ms, it enqueues the callback into the Callback Queue (not directly onto the stack).

3

Event Loop checks the stack

The event loop waits for the call stack to be completely empty. Only then does it take the callback from the queue and push it onto the stack to run.

Callback Queue vs Microtask Queue

This is the part that trips most people up. There are two separate queues, and they don't get equal treatment. The microtask queue (Promises) is emptied completely before the event loop takes even one macrotask from the callback queue.

Feature Microtask Queue Callback Queue (Macrotask)
Priority High: processed first Low: processed after all microtasks
Sources Promise.then/catch/finally, queueMicrotask(), MutationObserver setTimeout, setInterval, I/O callbacks, UI events
Drain behavior All microtasks run before next macrotask One per event loop iteration
Can starve macrotasks? Yes. An endless Promise chain blocks macrotasks No
Spec HTML5 Microtask Checkpoint HTML5 Event Loop Processing Model
Microtask vs Macrotask Ordering
console.log('1: Synchronous start');

setTimeout(() => console.log('5: setTimeout (macrotask)'), 0);

Promise.resolve()
    .then(() => console.log('3: Promise .then (microtask)'))
    .then(() => console.log('4: Chained Promise (microtask)'));

queueMicrotask(() => console.log('2.5: queueMicrotask (microtask)'));

console.log('2: Synchronous end');

// Output:
// 1: Synchronous start
// 2: Synchronous end
// 2.5: queueMicrotask (microtask)
// 3: Promise .then (microtask)
// 4: Chained Promise (microtask)
// 5: setTimeout (macrotask)
//
// WHY: After the synchronous code finishes (stack empties),
// ALL microtasks drain before the macrotask queue is checked.

The Event Loop Algorithm

Each pass of the loop (often called a "tick") follows the same order. Once you know it, you can predict the output of most async puzzles without running them:

1. Execute Script Run synchronous code Stack empty? No Keep running current code Yes 3. Drain Microtasks Run ALL pending microtasks 4. One Macrotask Dequeue & execute one callback Loop repeats

Event loop execution order: microtasks always drain before the next macrotask

Complete Execution Order Challenge
console.log('A');  // sync

setTimeout(() => console.log('B'), 0);  // macrotask

Promise.resolve()
    .then(() => {
        console.log('C');  // microtask
        setTimeout(() => console.log('D'), 0);  // schedules new macrotask
    })
    .then(() => console.log('E'));  // microtask (chained)

setTimeout(() => console.log('F'), 0);  // macrotask

console.log('G');  // sync

// Output: A, G, C, E, B, F, D
//
// Breakdown:
// Sync:       A, G
// Microtasks: C → E (all before any macrotask)
// Macrotask:  B (first setTimeout registered)
// Macrotask:  F (second setTimeout registered)
// Macrotask:  D (setTimeout registered inside Promise .then, after B and F)

Async/Await Under the Hood

Under the hood, async/await is built on Promises. Each await pauses the function and schedules the rest of it as a microtask, much like a .then callback. So async functions use exactly the same microtask queue as plain Promises.

Traditional Promise chaining:

function fetchUserData(id) {
    return fetch(`/api/users/${id}`)
        .then(res => {
            if (!res.ok) throw new Error('Network response was not ok');
            return res.json();
        })
        .then(user => {
            return fetch(`/api/posts?userId=${user.id}`);
        })
        .then(res => res.json())
        .then(posts => {
            return { user, posts };
        })
        .catch(err => {
            console.error('Failed to fetch:', err);
            throw err;
        });
}

Same logic with async/await, which I find easier to read:

async function fetchUserData(id) {
    try {
        const userRes = await fetch(`/api/users/${id}`);
        if (!userRes.ok) throw new Error('Network response was not ok');

        const user = await userRes.json();
        const postsRes = await fetch(`/api/posts?userId=${user.id}`);
        const posts = await postsRes.json();

        return { user, posts };
    } catch (err) {
        console.error('Failed to fetch:', err);
        throw err;
    }
}

What the engine actually does with await:

async function example() {
    console.log('Before await');   // sync, runs now
    const result = await somePromise;
    // ↑ Pauses here. Equivalent to:
    //   somePromise.then(result => {
    //       /* rest of function runs as microtask */
    //       console.log('After await:', result);
    //   });
    console.log('After await:', result);  // microtask
}

// Async functions always return a Promise, even if you return a plain value:
async function getValue() {
    return 42;  // same as: return Promise.resolve(42)
}

getValue().then(v => console.log(v));  // 42

Async Function Execution Order

Async/Await with Event Loop
async function asyncFn() {
    console.log('2: Inside async function (sync part)');
    await Promise.resolve();  // yields to microtask queue
    console.log('4: After await (microtask)');
}

console.log('1: Before calling asyncFn');
asyncFn();
console.log('3: After calling asyncFn (sync continues)');

// Output:
// 1: Before calling asyncFn
// 2: Inside async function (sync part)
// 3: After calling asyncFn (sync continues)
// 4: After await (microtask)
//
// The async function runs synchronously until the first await,
// then control returns to the caller. The rest resumes as a microtask.

Common Pitfalls and Best Practices

Pitfall 1: setTimeout(fn, 0) is not truly immediate

Even with a 0ms delay, setTimeout callbacks are macrotasks and always wait until the current script and all microtasks complete.

// This is wrong if you expect it to run immediately:
Promise.resolve().then(() => console.log('microtask'));
setTimeout(() => console.log('timeout 0'), 0);

// Output:
// microtask  ← runs first (microtask queue)
// timeout 0  ← runs second (macrotask queue)

Pitfall 2: Unhandled Promise rejections

If a Promise rejects and there's no .catch() or try/catch around the await, you get an unhandled rejection. Since Node.js 15 that kills the process by default, and the log line starts with [UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block...]. In the browser you just get an "Uncaught (in promise)" message in the console, which is easy to miss.

// Bad: unhandled rejection
async function badFetch() {
    const data = await fetch('/api/nonexistent');  // throws if network fails
    return data.json();
}

// Good: always handle errors
async function goodFetch() {
    try {
        const res = await fetch('/api/nonexistent');
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return await res.json();
    } catch (err) {
        console.error('Fetch failed:', err.message);
        return null;  // or re-throw for the caller to handle
    }
}

Pitfall 3: Sequential awaits when parallel is possible

Awaiting independent requests one after another is a very common slowdown. If they don't depend on each other, start them together with Promise.all().

// Slow: each awaits the previous (total: ~3 seconds)
async function slowVersion() {
    const user = await fetchUser(1);        // 1s
    const posts = await fetchPosts(1);      // 1s
    const comments = await fetchComments(1); // 1s
    return { user, posts, comments };
}

// Fast: all run in parallel (total: ~1 second)
async function fastVersion() {
    const [user, posts, comments] = await Promise.all([
        fetchUser(1),
        fetchPosts(1),
        fetchComments(1)
    ]);
    return { user, posts, comments };
}

// When some can fail independently, use Promise.allSettled
async function resilientVersion() {
    const results = await Promise.allSettled([
        fetchUser(1),
        fetchPosts(1),
        fetchComments(1)
    ]);
    return results.map(r => r.status === 'fulfilled' ? r.value : null);
}

Pitfall 4: Mixing async and sync in loops

Array.forEach does not await Promises. Use for...of for sequential async operations.

const ids = [1, 2, 3, 4, 5];

// WRONG: forEach doesn't await, all fire at once
ids.forEach(async (id) => {
    const data = await fetchData(id);
    processData(data);  // race condition risk
});

// CORRECT: sequential processing
for (const id of ids) {
    const data = await fetchData(id);
    processData(data);
}

// CORRECT: parallel processing (no concurrency limit, all requests start at once)
const results = await Promise.all(ids.map(id => fetchData(id)));
results.forEach(processData);

Practical Performance Patterns

A few patterns that come straight out of how the loop works. The first one keeps the UI responsive during heavy processing:

Breaking Up Long Tasks with setTimeout
// Process a large array without blocking the UI
async function processLargeArray(items) {
    const chunkSize = 100;

    for (let i = 0; i < items.length; i += chunkSize) {
        const chunk = items.slice(i, i + chunkSize);

        // Process this chunk synchronously
        chunk.forEach(item => processItem(item));

        // Yield control back to the event loop between chunks
        // This lets the browser render frames and handle user input
        await new Promise(resolve => setTimeout(resolve, 0));
    }
}

// In Node.js, use setImmediate for better performance:
await new Promise(resolve => setImmediate(resolve));
Implementing a Retry Mechanism with Exponential Backoff
async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000) {
    for (let attempt = 0; attempt <= retries; attempt++) {
        try {
            const res = await fetch(url, options);
            if (!res.ok) throw new Error(`HTTP ${res.status}`);
            return await res.json();
        } catch (err) {
            if (attempt === retries) throw err;

            // Wait with exponential backoff before retrying
            const backoff = delay * Math.pow(2, attempt);
            console.warn(`Attempt ${attempt + 1} failed. Retrying in ${backoff}ms...`);
            await new Promise(resolve => setTimeout(resolve, backoff));
        }
    }
}

// Usage
const data = await fetchWithRetry('/api/unstable-endpoint', {}, 4, 500);

Monitoring the Event Loop in Node.js

Detecting Event Loop Lag (Node.js)
// Measure how long the event loop is blocked
function measureEventLoopLag(intervalMs = 500) {
    let last = Date.now();

    setInterval(() => {
        const now = Date.now();
        const lag = now - last - intervalMs;
        if (lag > 50) {
            console.warn(`Event loop lag detected: ${lag}ms`);
        }
        last = now;
    }, intervalMs).unref();  // .unref() prevents this from keeping the process alive
}

measureEventLoopLag();

// In production, use the built-in perf_hooks module:
const { monitorEventLoopDelay } = require('perf_hooks');
const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();
setInterval(() => {
    console.log(`P99 event loop delay: ${histogram.percentile(99) / 1e6}ms`);
}, 5000);

What I check when async code misbehaves

Most event loop bugs I run into fall into a handful of buckets. This is roughly the order I go through them:

Debugging checklist

  • Is something synchronous hogging the stack? Open the Performance panel in DevTools and look for long tasks (the ones flagged in red, over 50ms). In Node, the monitorEventLoopDelay histogram above tells you the same thing.
  • Am I relying on setTimeout(fn, 0) for ordering? It runs after every pending microtask, and it can be clamped or throttled. If you need "after the current code", queueMicrotask or a resolved Promise is more predictable.
  • Is a microtask loop starving everything else? A Promise chain or queueMicrotask that keeps scheduling itself never lets a macrotask or a render through. The page freezes even though there's no visible while loop.
  • Are rejections being swallowed or crashing the process? Every await needs a try/catch somewhere up the chain, and fire and forget calls need their own .catch().
  • Are independent requests awaited one at a time? That's the easy win. Just don't reach for Promise.all over thousands of items, because it starts every request at once and can hammer your API or hit browser connection limits. Batch them or use a small concurrency limiter instead.

When I wouldn't bother with chunking via setTimeout: if the work is truly CPU bound and takes seconds, splitting it into chunks only spreads the pain around. Move it to a Web Worker (or a worker_threads worker in Node) and keep the main thread free for the UI or for incoming requests.

JavaScript Event Loop Async Promises Web APIs Performance Node.js
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.