Back to Explore
GuideVibeFix editorialUpdated Nov 20, 2026

When does your code actually run? A practical guide to the JavaScript event loop

JavaScript runs one thing at a time, and the order is not guesswork. This guide follows MDN's JavaScript execution model and the Using microtasks guide: heap, queue, and stack, one task then drained microtasks, why microtasks cut in line, long jobs that freeze the page, and the two legitimate uses of queueMicrotask.

Real photo: a hand holding a mechanical stopwatch against a dark background, the dial showing seconds

First, the boundaries of this guide. The site already has a practical guide to Promises and async/await, about the ways to write code that waits for a result to come back; this guide is not about how to write it, it is about time: when code actually runs, who runs first, who runs next, who can cut in line, and who freezes the page. There is also a practical guide to closures and scope, about how long a variable lives and who can see it; this guide is not about the life of a variable, only about the order of execution. The "Lighthouse Bookstore" used below is a fictional practice project: a small web tool that takes orders for a street-side bookstore — customers search for books, place orders, and pay, while the program checks stock, then works out the shipping fee, then submits the order. Every operation, code sample, and number built around it was invented to explain the technique, not a real record. Everything about the event loop, tasks, and microtasks comes from MDN's JavaScript execution model reference page and the Using microtasks guide; see each article's meta information and evidence record for sources. MDN's own examples, such as the foo, bar, and baz call stack, the 1 and 2 output order, and the factorial of 10, are the documentation's examples, not real user data.

Step 1: JavaScript is single-threaded — when it blocks, everything blocks

The first sentence of JavaScript's execution model is that an agent is a thread, which means the interpreter can only process one statement at a time. An agent is the specification's name for something that executes JavaScript; every window and every worker in the browser has its own agent. Single-threaded means only one piece of code runs at any moment. When all code is synchronous, that is fine, because progress can always be made. But once code needs to do something asynchronous, such as waiting for the network or for the user to click, the program cannot sit there waiting — JavaScript, as a web scripting language, is required to never block. MDN's own words are that the code that handles the completion of an asynchronous action is defined as a callback, which defines a job that gets placed into a job queue once the action is completed.

"Never blocking" does not mean the code runs fast; it means waiting for a result does not occupy the thread. While waiting for a fetch to return or an IndexedDB query to finish, the page can still handle user input, because "waiting" itself runs no code — what runs code is the callback that is placed in the queue after the action completes. Conversely, code that is running cannot be interrupted: once a function starts, it runs to completion in one go, and other code can only wait for it to finish. This is the core promise of the event loop model, and the premise behind every timing problem that follows.

Step 2: The engine and the host environment work as a pair

Executing JavaScript requires the cooperation of two pieces of software: the JavaScript engine and the host environment. The engine implements the ECMAScript language itself, parsing source code and executing it; the host environment provides the mechanisms for dealing with the outside world, such as the HTML DOM in a browser, or Node.js on the server. The engine handles the language, the host environment handles the outside world: timers, network requests, and user clicks are all provided by the host environment. MDN also notes that the specification occasionally talks about mechanisms defined in the HTML spec, which other host environments like Node.js or Deno often mimic, so this execution model mostly applies beyond the web as well.

Why does telling these two apart matter? When you write code, setTimeout, fetch, and addEventListener are not part of the language itself — the host environment gives them to you. Their behavior, such as which queue a timer callback lands in when it fires, is decided by the host environment and the specification together. The language only decides "how a function runs"; the host environment decides "when it gets its turn."

Step 3: Heap, queue, stack — three tools, each with its own job

Each agent maintains three things. The first is the heap: a large, mostly unstructured region of memory, where objects go when they are created. The second is the queue: known in HTML as the event loop, which enables asynchronous programming in JavaScript while being single-threaded. The queue is generally first-in-first-out: earlier jobs are executed before later ones. The third is the stack: the call stack, which transfers control flow by entering and exiting execution contexts. The stack is last-in-first-out: every job enters by pushing a new frame onto the empty stack, and exits by emptying the stack.

The three things each have their own job, so do not mix them up: the heap decides where objects live, the stack decides where a function is in its execution, and the queue decides who runs next. Many timing problems come down to confusing these three: assuming that an object sitting in the heap means code is running, or that a function entering the stack means a job is finished. Remember the division of labor: a job is finished only when the stack is empty; when the queue is empty, the agent waits for more jobs to be added.

Step 4: The call stack — functions press down layer by layer, and pop off as they finish

Start with how synchronous code runs. MDN's example is three functions: foo takes b, declares const a equal to 10 inside, and returns a plus b plus 11; bar takes x, declares const y equal to 3 inside, and returns foo(x times y); finally const baz equals bar(7), and baz is 42. Work it out: in bar(7), x is 7, y is 3, x times y is 21; in foo(21), a is 10, b is 21, and 10 plus 21 plus 11 equals 42. Yes, baz is 42.

The run goes like this: the job starts, the first frame is created, defining foo, bar, and baz, and calls bar(7), creating a second frame holding the parameter x and the local variable y; it works out 21, calls foo, creating a third frame holding the parameter b and the local variable a, which works out 42 and returns. When foo returns, the top frame is popped, and the call expression becomes the return value; when bar returns, another frame is popped, and baz is initialized to 42; when the job's source code reaches its end, the entrypoint frame is popped, the stack is empty, and the job is considered completed. An execution context is the smallest unit of execution, recording where the code is, which module or function it belongs to, which generator is currently executing, which variable bindings exist, and what this refers to. A popped frame is not necessarily gone forever: a generator function is the counterexample — calling gen() only creates a suspended execution context, and no code inside gen runs yet; calling g.next() once prints 1, calling it again prints 2, as the context is pushed up, suspended, and pushed up again, resuming where it stopped last time.

Step 5: One event loop iteration — one task, then drain the microtasks

With synchronous code covered, the rule for asynchronous code is: each job is pulled from the queue and executed, and while it runs it may create more jobs, which are added to the end of the queue; jobs can also be added when an asynchronous platform mechanism completes, such as a timer, I/O, or an event. A job is considered completed when the stack is empty, and only then is the next job pulled. The HTML event loop splits jobs into two categories: tasks and microtasks. Microtasks have higher priority, and the microtask queue is drained first before the task queue is pulled.

MDN's Using microtasks guide states the order of one iteration plainly: the event loop handles the oldest runnable task in the task queue during a single iteration; after that, microtasks will be executed until the microtask queue is empty, and then the browser may choose to update rendering; then the browser moves on to the next iteration of the event loop. In other words, one iteration has three steps: one task, drain the microtasks, maybe render. Rendering does not happen every iteration — the browser "may" update rendering — but microtasks are always drained every iteration. Remember this order, and every "why did this print first" question has its answer in these three steps.

Step 6: Microtasks cut in line, and recursive microtasks starve rendering

Tasks and microtasks look alike, but they are handled in two key different ways. First, each time a task exits, the event loop checks whether the task is returning control to other JavaScript code; if not, it runs all of the microtasks in the microtask queue. The microtask queue is therefore processed multiple times per iteration of the event loop, including after handling events and other callbacks. Second, if a microtask adds more microtasks to the queue, those newly added microtasks execute before the next task is run, because the event loop will keep calling microtasks until there are none left in the queue, even if more keep getting added.

The second point is where the danger lies. MDN gives a direct warning: since microtasks can themselves enqueue more microtasks, and the event loop continues processing microtasks until the queue is empty, there is a real risk of getting the event loop endlessly processing microtasks — be cautious with how you go about recursively adding microtasks. A loop that keeps adding microtasks will leave later tasks waiting forever and rendering waiting forever, and the page looks dead. A microtask is not a "faster" task; it is a task that cuts in line. Cut in line too many times, and the people behind never get served. Use microtasks only when there is no other solution, or when creating frameworks or libraries that need them — do not use them as an everyday tool.

Step 7: Remember the numbers 1, 2, 3, 4

Timing problems are best memorized as numbers. MDN's Promises guide has one set: Promise.resolve().then printing 2, followed by console.log(1), always prints 1, then 2 — because the then callback is placed on the microtask queue and only runs after the current synchronous code has finished and the execution stack is empty. The execution model page gives a fuller version: wait(0).then printing 4, then two thens printing 2 and 3, then console.log(1), with the output 1, 2, 3, 4. Microtasks run before timer tasks, so with the same zero-millisecond wait, the Promise callback runs before the setTimeout callback.

The microtask guide has another comparison: first log "Main program started," then schedule a regular timeout callback with setTimeout at 0 milliseconds, then enqueue an urgent callback with queueMicrotask, and finally log "Main program exiting." The output is: Main program started, Main program exiting, the urgent callback, then the regular timeout callback. The main program's output appears first, followed by the microtask, followed by the timeout's callback, because when the task handling the main program exits, the microtask queue gets processed before the task queue on which the timeout callback sits. One sentence tells them apart: tasks and microtasks are kept on separate queues, and microtasks run first. setTimeout with 0 milliseconds does not mean "run right now" — it means "join the end of the task queue and wait for the next iteration"; queueMicrotask is what means "run as soon as this task ends."

Step 8: Each job runs to completion before the next — that is why the order is predictable

The event loop model offers a useful property: each job is processed completely before any other job is processed. This means that whenever a function runs, it cannot be preempted and will run entirely before any other code runs. MDN's example is: first Promise.resolve(), then let i equal 0, then two promise.then callbacks, each adding 1 to i and printing it. It looks like a race condition, but the output is fully predictable: 1, then 2. Because each job runs to completion before the next one is executed, the overall order is always i += 1, console.log(i), i += 1, console.log(i) — and never i += 1, i += 1, console.log(i), console.log(i).

This guarantee is the foundation for reasoning about a program: data that a function is halfway through changing will never be seen mid-change by other code. But it has a cost: if a job takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog, but the real fix is to make job processing short and, if possible, cut down one job into several jobs. A long job is not "slow code" — it is code holding the thread and refusing to let go, and while it holds the thread, the click callbacks waiting in the queue can only wait.

Step 9: A long job freezes the page — cut it small and requeue

The Lighthouse Bookstore search page shows this well. Suppose a search returns thousands of results, and rendering them all in a single job freezes the page for several seconds, during which nothing responds to a click. The fix is to cut it small: render only 50 results at a time, then use setTimeout with 0 milliseconds or requestAnimationFrame to queue the rest for the next job, giving up the thread in between so the user's clicks and scrolling can get in. Cutting small does not make it slower — it turns one long wait into many short waits, and between each short wait the page can breathe.

Two kinds of "waiting" must be told apart here: waiting for the network or for user input does not occupy the thread; running a loop for several seconds does occupy the thread. The first is what the event loop is built to handle; the second is a long job the code created for itself. The test is a single question: while this code runs, can the page still respond? If not, cut it. And when cutting, note the difference: setTimeout with 0 milliseconds queues to the end of the task queue, while queueMicrotask cuts into the microtask queue — if you want the page to breathe and rendering to get a chance, use a task, not a microtask. No matter how many microtasks cut in, rendering still has to wait.

Step 10: The two legitimate uses of queueMicrotask

Microtasks are not forbidden — they just belong only where they belong. MDN gives two legitimate uses. The first is ensuring consistent ordering: with a cached result, the code fires the load event synchronously right away; without a cache, it goes through fetch's Promise, and the order of operations differs between the two branches — without a cache, the logs read "Fetching data…", "Data fetched", "Loaded data"; with a cache, "Loaded data" jumps ahead of "Data fetched." The fix is to wrap the cached branch in queueMicrotask as well, so setting the data and firing the event both happen inside a microtask, and the two branches behave in the same order. The point is: whether data arrives synchronously or asynchronously, the order the caller sees must be the same — do not make the caller guess.

The second is batching operations: sendMessage pushes each message onto an array when called; if it is the first one, it enqueues a microtask, and when the microtask runs it sends the whole array in one fetch. Because the microtask only runs after the current task exits, multiple calls to sendMessage in the same iteration all land in the same array and go out in the same fetch. When the microtask runs, the array may already hold many messages, sent at once, saving the overhead of multiple calls. The key is the length check: a microtask is enqueued only when the array length is 1; later calls just push onto the array and enqueue nothing new. Both uses share one idea: they exploit the moment when "a microtask runs after the current task exits, before any other callback" — not the idea of a microtask as a "faster" timer.

Step 11: The factorial of 10 — a microtask waits for the main program to exit

The microtask guide has one more example worth running by hand: a doWork function first enqueues a microtask with queueMicrotask, then computes the factorial of 10. The computation starts with result at 1 and multiplies i from 2 to 10: 1 times 2 is 2, times 3 is 6, times 4 is 24, times 5 is 120, times 6 is 720, times 7 is 5040, times 8 is 40320, times 9 is 362880, times 10 is 3628800. So 10! equals 3628800. The main program first logs "Main program started," then schedules a regular timeout callback with setTimeout at 0 milliseconds, then logs "10! equals 3628800," and finally logs "Main program exiting." The urgent callback inside the microtask only runs after the whole main program exits, the task exits, and the stack is empty — never the moment doWork returns.

This sentence is worth remembering on its own: a microtask is not processed when the function exits, but when the main program exits. A function exiting and a task exiting are two different things: a function exiting only removes one frame from the stack, while a task exiting means the stack is empty. While doWork is computing the factorial, the main program's frame is still on the stack, so the microtask can only wait. Many timing bugs come down to exactly this: assuming "I called queueMicrotask, so it should run on the next line," when in fact it waits until the whole task finishes. To verify, run this example in the console and check whether "Main program exiting" always comes before the urgent callback.

Step 12: 120 timing incidents in one quarter — check yourself against the chart

Bar chart of 120 event-loop timing incidents in one quarter in the fictional Lighthouse Bookstore project, by cause

The chart above shows a fictional quarter for the Lighthouse Bookstore project: 120 incidents related to event-loop timing in total. A long job holding the thread, leaving the page unclickable for seconds: 42, or 35.0%, the largest group; microtasks recursively adding microtasks, so rendering never got its turn: 28, or 23.3%; believing setTimeout with 0 milliseconds means "run right now," so the order came out wrong: 24, or 20.0%; guessing the order of two then callbacks wrong, assuming they would interleave: 14, or 11.7%; the cached branch and the network branch running in different orders, so the caller sometimes got data and sometimes did not: 12, or 10.0%. 42 + 28 + 24 + 14 + 12 = 120, and the books balance. These numbers are invented examples, meant to show at a glance that the first two groups together are almost sixty percent — and that they are the same root cause in different spellings: not knowing "who runs first, who runs next, and who cuts in line."

Checklist: after writing async code, tick each item

First, a running function cannot be interrupted — it runs to completion in one go before the next one starts. Second, one loop iteration has three steps: one task, drain the microtasks, maybe render. Third, microtasks run before tasks, and setTimeout with 0 milliseconds joins the end of the task queue — it does not run right now. Fourth, microtasks cut in line, and recursively adding microtasks starves rendering and later tasks. Fifth, a job that runs too long freezes the page, so long jobs must be cut small and queued for the next task. Sixth, to let the page breathe and give rendering a chance, use a task, not a microtask. Seventh, whether data arrives synchronously or asynchronously, the order the caller sees must be consistent — when needed, use queueMicrotask to wrap the synchronous branch into a microtask too. Eighth, a microtask runs when the whole task exits and the stack is empty, not when a function returns. Ninth, a Promise's then callback is a microtask, while the executor itself runs synchronously. If any item cannot be answered, go back to its section and read it again — that is worth more than memorizing ten more APIs.

Views 1Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding
Real photo: a laptop, tablet, and phone on a wooden table showing the same green-leaf website, the phone view with navigation in one column, a potted plant nearby
Guide
Squashed on phones? Responsive layout and media queries, explained plainly

One page should stand up on a phone, a tablet, and a computer. This guide follows MDN's Responsive web design, Using media queries, and the viewport meta reference: fluid HTML, the viewport tag, fluid grids and max-width, images that never burst their container, media query syntax, breakpoints set by content, mobile first, responsive type, testing capability instead of width, and a pre-launch checklist.

Mobile AppsDesign ExperienceFrontend Engineering
Real photo: a Casio scientific calculator on a wooden desk showing 123456789 + 987654321 = 1111111110, beside handwritten math notebooks, a pen, a mug, and a laptop edge
Guide
Don't let 0.1 + 0.2 break your bill: JavaScript numbers and Math, explained plainly

Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.

Tool TipsFrontend EngineeringAI Coding