惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Forbes - Security
Forbes - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Palo Alto Networks Blog
Martin Fowler
Martin Fowler
T
Threatpost
D
Docker
S
Schneier on Security
M
MIT News - Artificial intelligence
G
Google Developers Blog
L
LINUX DO - 热门话题
J
Java Code Geeks
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
IT之家
IT之家
博客园 - Franky
C
Cyber Attacks, Cyber Crime and Cyber Security
K
Kaspersky official blog
Google DeepMind News
Google DeepMind News
N
News and Events Feed by Topic
V
Vulnerabilities – Threatpost
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
人人都是产品经理
人人都是产品经理
Spread Privacy
Spread Privacy
T
Tailwind CSS Blog
爱范儿
爱范儿
阮一峰的网络日志
阮一峰的网络日志
U
Unit 42
C
CERT Recently Published Vulnerability Notes
The GitHub Blog
The GitHub Blog
Simon Willison's Weblog
Simon Willison's Weblog
NISL@THU
NISL@THU
MongoDB | Blog
MongoDB | Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
H
Heimdal Security Blog
Recorded Future
Recorded Future
云风的 BLOG
云风的 BLOG
SecWiki News
SecWiki News
P
Privacy International News Feed
P
Proofpoint News Feed
O
OpenAI News
B
Blog
腾讯CDC
F
Full Disclosure
Apple Machine Learning Research
Apple Machine Learning Research
T
Tor Project blog
H
Hacker News: Front Page
Project Zero
Project Zero
Hugging Face - Blog
Hugging Face - Blog
C
Cisco Blogs
S
Security Affairs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
The JavaScript Event Loop: Why Your Code Doesn't Do What You Think It Does
Jack Pritom · 2026-05-15 · via DEV Community

JavaScript is single-threaded. One thread. One call stack. One thing at a time.

And yet — you've written code that fetches data from an API while animating a loading spinner while handling button clicks while running a countdown timer. How? How does one thread do all of that without freezing?

The answer is the event loop — arguably the most misunderstood piece of the JavaScript runtime. Most developers use it every day without ever truly seeing it. They write setTimeout, Promise.then(), async/await, and fetch() like they're magic spells, and they mostly work — until they don't.

Until you've hit a bug where a setTimeout(..., 0) fires after something it should have fired before. Until a Promise resolves in an order that makes no logical sense to you. Until your UI freezes solid because a loop ran too long. That's when you realize: you've been flying blind.

Understanding the event loop isn't just academic. It's the difference between writing JavaScript that works and writing JavaScript that you understand. It explains why async/await is not the same as threads, why microtasks beat macrotasks, and why your beautiful Promise chain sometimes feels like it has a mind of its own.

This article is the deep dive nobody wrote clearly enough. By the end, you'll be able to look at any piece of async JavaScript and trace — in your head, step by step — exactly what order things will execute and why.


What We'll Cover

  1. The Single-Threaded Reality
  2. The Call Stack — JavaScript's Working Memory
  3. The Web APIs Layer — Where Async Work Actually Happens
  4. The Callback Queue (Macrotask Queue)
  5. The Microtask Queue — The Queue That Jumps the Line
  6. The Event Loop — The Conductor Tying It All Together
  7. setTimeout and setInterval — What They Actually Promise
  8. Promises and the Microtask Queue
  9. async/await — Syntactic Sugar with Real Consequences
  10. Real-World Execution Order Puzzles (With Solutions)
  11. Pitfalls That Will Bite You in Production
  12. Conclusion — The Mental Model You'll Keep Forever

1. The Single-Threaded Reality

Let's start with what "single-threaded" actually means, because it's more nuanced than it sounds.

A thread is a sequence of instructions a CPU can execute. Some languages — Java, Go, C++ — are multi-threaded, meaning they can genuinely run multiple instruction sequences simultaneously on different CPU cores. They share memory, they can race each other, and you need mutexes and semaphores and all sorts of painful synchronization primitives to keep them from stepping on each other.

JavaScript deliberately chose not to do that. One thread. No shared memory races. No deadlocks. No mutexes.

But here's the thing people miss: JavaScript is single-threaded, but the browser (or Node.js) is not. The runtime environment — Chrome, Firefox, Node — is heavily multi-threaded. It has threads for network I/O, file I/O, timers, rendering, garbage collection, and more. JavaScript itself runs on one thread, but it delegates slow work to those other threads.

The event loop is the mechanism by which results from those other threads get handed back to your JavaScript code, safely, one at a time.


2. The Call Stack — JavaScript's Working Memory

The call stack is where JavaScript tracks what it's currently executing. It's a stack data structure — last in, first out — and every time you call a function, a new stack frame gets pushed on top. When the function returns, that frame gets popped off.

function greet(name) {
    return `Hello, ${name}!`;         // 3. This executes, returns
}

function main() {
    const message = greet("Fatima");  // 2. greet() is pushed onto stack
    console.log(message);             // 4. console.log is pushed, executes, pops
}

main();                               // 1. main() is pushed onto stack

Enter fullscreen mode Exit fullscreen mode

Execution trace:

[] → [main] → [main, greet] → [main] → [main, console.log] → [main] → []

Enter fullscreen mode Exit fullscreen mode

The call stack is synchronous and blocking. If you put a while(true) loop in there, the stack never clears. Nothing else runs. Your UI freezes. The browser tab hangs.

This is why long-running synchronous operations are the enemy. They hold the stack hostage.


3. The Web APIs Layer — Where Async Work Actually Happens

When you call fetch(), setTimeout(), addEventListener(), or fs.readFile() — you are not running JavaScript. You're calling into the Web APIs layer (in the browser) or the Node.js C++ APIs layer.

Think of it like handing off a task to a dedicated department:

  • "Go make this HTTP request. Come back when you have a response."
  • "Set a timer for 500ms. Come back when it fires."
  • "Watch this DOM element for a click. Come back when it happens."

JavaScript doesn't wait. It just hands off the task, registers a callback, and moves on. The API does the work — off the main thread, in the background — and when it's done, it puts your callback in a queue.

console.log("1 — Starting");

// This call goes to the Timer Web API.
// JavaScript does NOT wait here. It just registers the callback and moves on.
setTimeout(() => {
    console.log("3 — Timer fired");
}, 1000);

console.log("2 — Already past the setTimeout");

// Output:
// 1 — Starting
// 2 — Already past the setTimeout
// (1 second later...)
// 3 — Timer fired

Enter fullscreen mode Exit fullscreen mode

JavaScript handed the timer to the browser, said "call me back in 1000ms," and kept running. That's non-blocking I/O in a nutshell.


4. The Callback Queue (Macrotask Queue)

When an async operation completes — a timer fires, a network response arrives, a click event triggers — the callback associated with it gets placed in the callback queue (also called the macrotask queue or task queue).

This queue holds tasks waiting for their turn to run. They can't jump onto the call stack directly. They have to wait.

Common sources of macrotasks:

  • setTimeout callbacks
  • setInterval callbacks
  • I/O callbacks (file reads, network responses in Node.js)
  • UI event handlers (click, keydown, scroll)
  • postMessage callbacks
  • setImmediate (Node.js only)

The queue is processed one task at a time. Each task runs to completion — no interruption. If a task takes 500ms, the browser is locked for 500ms. This is why you'll sometimes see the browser devtools warn about "long tasks."


5. The Microtask Queue — The Queue That Jumps the Line

Here's where most developers' mental models break down.

There are two queues, not one. The second is the microtask queue, and it has priority over the callback queue. Every single time.

Sources of microtasks:

  • Promise.then() / Promise.catch() / Promise.finally() callbacks
  • queueMicrotask()
  • MutationObserver callbacks
  • await (under the hood, it's a promise)

The rule is this: after every task completes (or after the initial script finishes), the entire microtask queue is drained before the next macrotask runs.

Not one microtask. All of them. And if a microtask schedules another microtask, that one runs too, before any macrotask.

console.log("1 — Script start");

setTimeout(() => console.log("5 — setTimeout"), 0);  // Macrotask

Promise.resolve()
    .then(() => console.log("3 — Promise 1"))         // Microtask
    .then(() => console.log("4 — Promise 2"));        // Microtask (scheduled by microtask)

console.log("2 — Script end");

// Output:
// 1 — Script start
// 2 — Script end
// 3 — Promise 1
// 4 — Promise 2
// 5 — setTimeout

Enter fullscreen mode Exit fullscreen mode

Even though setTimeout was registered before the Promise chain, it fires after both promise callbacks. The entire microtask queue empties first.


6. The Event Loop — The Conductor Tying It All Together

The event loop is the algorithm that orchestrates all of this. Here it is, in pseudocode:

while (true) {
    // 1. Run the current task (or the initial script)
    executeCurrentTask();

    // 2. Drain the entire microtask queue
    while (microtaskQueue.isNotEmpty()) {
        microtaskQueue.dequeue().execute();
        // Note: if this microtask adds more microtasks, those run too
    }

    // 3. Maybe render (browser decides, typically ~60fps)
    if (renderingNeeded) {
        render();
    }

    // 4. Pick the next macrotask from the callback queue
    if (callbackQueue.isNotEmpty()) {
        currentTask = callbackQueue.dequeue();
    }
}

Enter fullscreen mode Exit fullscreen mode

The loop is always watching. When the call stack is empty and there are tasks waiting, it picks the next one and runs it. But it always drains microtasks first.

Here's the full picture as a diagram:

┌─────────────────────────────────────────────────┐
│                 Your JS Code                    │
│                  Call Stack                     │
└────────────────────┬────────────────────────────┘
                     │
           calls Web APIs / Node APIs
                     │
                     ▼
┌─────────────────────────────────────────────────┐
│            Web APIs / C++ APIs                  │
│   (setTimeout, fetch, fs.readFile, events...)   │
└──────┬──────────────────────┬───────────────────┘
       │                      │
       ▼                      ▼
┌─────────────┐      ┌──────────────────┐
│  Microtask  │      │  Callback Queue  │
│    Queue    │      │  (Macrotask Q.)  │
│  (Promises) │      │  (setTimeout,    │
│             │      │   I/O, events)   │
└──────┬──────┘      └────────┬─────────┘
       │                      │
       └──────────┬───────────┘
                  │
                  ▼
           ┌──────────────┐
           │  Event Loop  │ ◄── "Is the stack empty?
           │              │      Drain microtasks.
           └──────────────┘      Then run next macrotask."

Enter fullscreen mode Exit fullscreen mode


7. setTimeout and setInterval — What They Actually Promise

setTimeout(fn, delay) does not guarantee your callback runs after exactly delay milliseconds. It guarantees the callback will be added to the macrotask queue no sooner than delay milliseconds from now.

If the call stack is busy, the callback waits — no matter how long.

const start = Date.now();

// This timer should fire after 100ms.
setTimeout(() => {
    // In reality, this will log something much larger than 100.
    console.log(`Fired after ${Date.now() - start}ms`);
}, 100);

// This synchronous loop blocks the call stack for ~500ms.
// The setTimeout callback is in the queue, but it can't run yet.
const blockUntil = Date.now() + 500;
while (Date.now() < blockUntil) {
    // spinning — this is exactly the kind of code that freezes UIs
}

// Output: something like "Fired after 502ms" — not 100ms

Enter fullscreen mode Exit fullscreen mode

setTimeout(..., 0) is often used as a trick to defer code to the next iteration of the event loop — but it's still a macrotask, so it yields to all pending microtasks first.


8. Promises and the Microtask Queue

Every .then(), .catch(), and .finally() callback is a microtask. This is baked into the Promise specification — not a browser decision.

console.log("start");

const p = new Promise((resolve) => {
    // The executor function runs SYNCHRONOUSLY, right now.
    console.log("inside Promise constructor");
    resolve("done");
});

p.then((value) => {
    // This runs as a MICROTASK — after the current synchronous code finishes.
    console.log("then:", value);
});

console.log("end");

// Output:
// start
// inside Promise constructor
// end
// then: done

Enter fullscreen mode Exit fullscreen mode

The Promise constructor runs synchronously. The .then() callback does not — it queues as a microtask and runs after the current call stack empties.

This surprises a lot of developers. They expect the .then() to run right after resolve(). It doesn't. It politely waits its turn.


9. async/await — Syntactic Sugar with Real Consequences

async/await is beautiful syntax. But it's crucial to understand what it compiles to, because the semantics are the same as Promises — just dressed up.

// This async function...
async function fetchUser(id) {
    const response = await fetch(`/api/users/${id}`);
    const user = await response.json();
    return user;
}

// ...is roughly equivalent to this Promise chain:
function fetchUser(id) {
    return fetch(`/api/users/${id}`)
        .then(response => response.json())
        .then(user => user);
}

Enter fullscreen mode Exit fullscreen mode

Every await is a suspension point. When you await something, the async function pauses and hands control back to the caller. The code after the await is scheduled as a microtask to run when the awaited Promise resolves.

async function main() {
    console.log("1 — before await");

    await Promise.resolve();  // Suspends here. Resumes as microtask.

    console.log("3 — after await");  // Runs as microtask
}

main();
console.log("2 — after calling main()");

// Output:
// 1 — before await
// 2 — after calling main()
// 3 — after await

Enter fullscreen mode Exit fullscreen mode

When main() hits the await, it suspends. JavaScript keeps running synchronously past the main() call and logs "2". Then the microtask runs and logs "3".

async/await does not make code run on a different thread. It's still single-threaded. It just makes asynchronous code look synchronous while still yielding the call stack between operations.


10. Real-World Execution Order Puzzles

Let's put it all together. Work through these before peeking at the answers.

Puzzle 1

console.log("A");

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

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

console.log("E");

Enter fullscreen mode Exit fullscreen mode

Answer

A
E
C
B
D

Enter fullscreen mode Exit fullscreen mode

Why:

  1. A — synchronous
  2. setTimeout B → macrotask queue
  3. Promise → microtask queue
  4. E — synchronous
  5. Call stack empty → drain microtasks: C logs, setTimeout D → macrotask queue
  6. No more microtasks → run next macrotask: B
  7. No more microtasks → run next macrotask: D

Puzzle 2

async function alpha() {
    console.log("alpha 1");
    await null;
    console.log("alpha 2");
}

async function beta() {
    console.log("beta 1");
    await null;
    console.log("beta 2");
}

console.log("start");
alpha();
beta();
console.log("end");

Enter fullscreen mode Exit fullscreen mode

Answer

start
alpha 1
beta 1
end
alpha 2
beta 2

Enter fullscreen mode Exit fullscreen mode

Why:

  1. start — sync
  2. alpha() runs: logs alpha 1, hits await, suspends → schedules microtask
  3. beta() runs: logs beta 1, hits await, suspends → schedules microtask
  4. end — sync
  5. Call stack empty → drain microtasks: alpha 2, then beta 2

11. Pitfalls That Will Bite You in Production

Starving the render with too many microtasks

Because microtasks all run before the browser gets a chance to render, an infinite microtask loop will lock up the UI just as badly as a synchronous loop — possibly worse, because it looks like async code.

// ❌ Don't do this — infinite microtask loop, browser never renders
function infiniteMicrotasks() {
    Promise.resolve().then(infiniteMicrotasks);
}
infiniteMicrotasks();

// ✅ If you need to yield to rendering, use setTimeout or requestAnimationFrame
function yieldToRender(fn) {
    requestAnimationFrame(fn);  // Runs after the next render frame
}

Enter fullscreen mode Exit fullscreen mode


Unhandled Promise rejections are silent killers

// ❌ This rejection is unhandled. In older Node versions it silently fails.
//    In modern Node, it crashes the process.
async function riskyOperation() {
    throw new Error("Something went wrong");
}

riskyOperation(); // Missing await AND missing .catch()

// ✅ Always handle rejections
riskyOperation().catch(err => console.error("Caught:", err));

// ✅ Or use try/catch with await
try {
    await riskyOperation();
} catch (err) {
    console.error("Caught:", err);
}

Enter fullscreen mode Exit fullscreen mode


await inside loops — sequential vs parallel

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

// ❌ Sequential — each fetch waits for the previous to finish.
//    Total time: sum of all request times. Slow.
async function fetchSequential(ids) {
    const results = [];
    for (const id of ids) {
        const user = await fetchUser(id);  // Waits here before next iteration
        results.push(user);
    }
    return results;
}

// ✅ Parallel — all requests fire at once.
//    Total time: slowest single request. Fast.
async function fetchParallel(ids) {
    const promises = ids.map(id => fetchUser(id));  // Fire all, don't await yet
    return await Promise.all(promises);              // Wait for all to complete
}

Enter fullscreen mode Exit fullscreen mode


The forEach async trap

const data = [1, 2, 3];

// ❌ forEach doesn't await async callbacks. It fires them all and moves on.
//    "Done" prints before any of the async work finishes.
data.forEach(async (item) => {
    await processItem(item);
});
console.log("Done");  // Prints immediately — not actually done

// ✅ Use for...of when you need to await inside a loop
for (const item of data) {
    await processItem(item);
}
console.log("Done");  // Now actually done

Enter fullscreen mode Exit fullscreen mode


12. Conclusion — The Mental Model You'll Keep Forever

Here's the mental model, distilled:

JavaScript has one thread, one call stack. It can only do one thing at a time. Async operations — timers, network calls, I/O — get delegated to the browser/Node runtime, which handles them off the main thread. When they complete, callbacks get queued.

Two queues exist. The microtask queue (Promises, await) and the macrotask queue (setTimeout, I/O, events). After every task — including the initial script — the entire microtask queue drains before the next macrotask runs.

async/await is Promises in a costume. Beautiful, readable, but the same underlying semantics. Every await suspends the function and schedules the rest as a microtask.

Once this model clicks, async JavaScript stops being magic. You can trace any execution order in your head. You know why setTimeout(..., 0) doesn't always mean "immediately." You know why a Promise resolves after your synchronous code. You know why that forEach with await inside was never actually doing what you thought.

The event loop is the heartbeat of JavaScript. Understanding it doesn't just make you better at debugging async bugs — it makes you better at writing async code in the first place. You start structuring things around how JavaScript actually works, rather than how you wish it worked.

Go write something async. Then trace through it mentally. If you get the order right — you've got it.


Further reading: MDN's Concurrency model and the event loop, Jake Archibald's classic talk "In The Loop" (JSConf Asia), and the WHATWG HTML spec on the event loop processing model if you really want to go deep.