1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Event Loop Explained: Call Stack, Microtasks and Timers With Examples

Why does a setTimeout of zero still run last? How can one thread handle so much at once? Learn how the event loop really works, test it with code we ran, and solve the classic interview question.

9 min read
JavaScript event loop explained: call stack, microtasks and timers with examples

Key takeaways

  • JavaScript runs your code on a single thread, one piece at a time.
  • When the call stack is empty, all microtasks run first, and then one task.
  • setTimeout(fn, 0) means “as soon as possible after a minimum delay”, not “now”.
  • Long synchronous work blocks everything, so split it up or move it to a worker.

Run a few lines with setTimeout and a promise, and the output order may surprise you. The JavaScript event loop explains why. It is the mechanism that lets a single-threaded language handle timers, network calls and clicks without freezing.

Once you understand it, a whole class of confusing bugs starts to make sense. We ran each example on Node.js 24, and the output comes from that run. The core ordering rules also apply in browsers, and we point out where Node.js differs. You will get more from this if you already know the basics of JavaScript promises.

Why the event loop exists

JavaScript executes your code on one main thread, so only one piece of it runs at a time. If it simply waited for a network request, a page would freeze until the response came back.

So JavaScript does not wait. Slow work is handed to the host environment, meaning the browser or Node.js, which can handle it in the background. When that work finishes, a callback is placed in a queue. The event loop’s job is to move queued callbacks onto the stack when it is free.

Think of a chef working alone. The chef puts a dish in the oven and sets a timer, rather than staring at it. When the timer rings, the task goes on a list, and the chef picks it up after finishing what is currently in hand.

The moving parts

Part What it does Examples
Call stack Tracks the functions currently running Your synchronous code
Host APIs Do work outside your code Timers, fetch, file reads
Task queue Holds callbacks that are ready to run setTimeout, clicks, I/O
Microtask queue Holds higher-priority callbacks .then, await, queueMicrotask
Event loop Decides what runs next Runs continuously

Tasks are sometimes called macrotasks. Strictly speaking, there may be several task sources, and the exact details differ between environments.

The rules

  1. Run all synchronous code until the call stack is empty.
  2. Run all microtasks, including any new ones added along the way.
  3. In a browser, render an update if one is due.
  4. Take one task from a queue and run it.
  5. Go back to step 2.

The most important detail: all microtasks, then one task. Most event loop puzzles are solved by applying that single rule.

See the order

console.log("1 sync");
setTimeout(() => console.log("5 timeout"), 0);
Promise.resolve().then(() => console.log("3 promise"));
queueMicrotask(() => console.log("4 microtask"));
console.log("2 sync");

// 1 sync
// 2 sync
// 3 promise
// 4 microtask
// 5 timeout

Here is what happened. The two console.log lines are synchronous, so they ran first. The promise callback and queueMicrotask went into the microtask queue, and they ran as soon as the stack was empty, in the order they were added. The timer callback had to wait for a task turn, even though its delay was zero.

Microtasks run between timers

After every single task, the microtask queue is emptied again. This example proves it:

setTimeout(() => {
  console.log("timer 1");
  Promise.resolve().then(() => console.log("promise inside timer 1"));
}, 0);
setTimeout(() => console.log("timer 2"), 0);

// timer 1
// promise inside timer 1
// timer 2

The promise, which was created during the first timer, ran before the second timer. Modern browsers and Node.js 11 and later behave this way.

Where await fits

await splits a function in two. Everything before it runs synchronously, and everything after it is scheduled as a microtask. This surprises many people:

async function task() {
  console.log("A before await");
  await null;
  console.log("C after await");
}

task();
console.log("B after calling task");

// A before await
// B after calling task
// C after await

An async function does not start in the background. It runs on the same thread until it reaches its first await. That even applies when awaiting something that is not a real promise, like null. See our JavaScript async/await guide for more on this syntax.

Blocking the loop

While synchronous code runs, nothing else can. To show this, we set a timer for 0 ms, then kept the thread busy for half a second:

const start = Date.now();
setTimeout(() => console.log("timer ran after", Date.now() - start, "ms"), 0);
while (Date.now() - start < 500) {}

// timer ran after about 500 ms

The timer’s delay is a minimum, not a guarantee. It ran only when the stack became free. On a web page, a long loop like this means that clicks do not respond and animations stop. On a server, every other request has to wait, which is why one slow synchronous call can hurt all users of a Node.js process.

Common causes of blocking include huge loops, parsing very large JSON, synchronous file functions like readFileSync in request handlers, and catastrophic regular expressions.

Tip: In Chrome DevTools, the Performance panel marks tasks longer than 50 ms as long tasks. It is a quick way to find what is making a page feel sluggish.

Staying responsive

For heavy work, give the event loop a chance to breathe. One way is to pause on a timer now and then, which lets other tasks run:

const items = [0, 1, 2, 3, 4];

async function processAll() {
  for (const item of items) {
    if (item === 2) await new Promise((r) => setTimeout(r, 0));
    console.log("item", item);
  }
}

setTimeout(() => console.log("other work gets a turn"), 0);
processAll();

// item 0
// item 1
// other work gets a turn
// item 2
// item 3
// item 4

The other timer ran in the middle, because we yielded with a real task. Real code would yield every so many items or milliseconds. For truly CPU-heavy work, such as image processing, use a Web Worker in browsers or a worker thread in Node.js, which run on separate threads.

Microtask starvation

Since the loop empties the microtask queue completely before moving on, a microtask that keeps scheduling more can stop everything else. We tested this with 100,000 chained microtasks:

let count = 0;
let timerFired = false;
setTimeout(() => { timerFired = true; }, 0);

function spin() {
  count++;
  if (count < 100000) queueMicrotask(spin);
  else console.log("timer fired during microtasks?", timerFired);
}
queueMicrotask(spin);

// timer fired during microtasks? false

The timer could not run until all of them were done. If that chain never ended, timers would never fire, and in a browser the page would never repaint. Note that yielding with await on a resolved promise does not help here, because it just adds another microtask. You need a real task, such as a timer, to give others a turn.

Rendering in browsers

A browser usually gets its chance to paint between tasks. That explains a common bug:

spinner.hidden = false;
doHeavyWork();              // blocks the thread
spinner.hidden = true;

The spinner never appears, because the browser had no opportunity to render between those lines. To fix it, let a frame pass before the heavy work begins, or move that work to a worker. For code that changes visuals, requestAnimationFrame runs just before the next paint, which makes it the right tool for animation.

Node.js differences

Node.js has its own event loop with several phases, including timers, I/O polling and setImmediate. It also has process.nextTick, which runs in its own queue. Here is what we saw when running these from inside an async function:

setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));

// promise
// nextTick
// immediate
// timeout

Many articles state that nextTick always beats promises, and that a timer beats setImmediate. Our result shows that it is not that simple. Our code was already running within a microtask, so the promise queue carried on first. And the order of setTimeout and setImmediate is known to vary depending on where they are called from. So do not write code that depends on the exact order of these. If one thing must happen after another, chain them explicitly.

Interview quiz

Try to work out the order before you read the answer:

console.log("a");
setTimeout(() => console.log("b"), 0);
Promise.resolve().then(() => {
  console.log("c");
  setTimeout(() => console.log("d"), 0);
  Promise.resolve().then(() => console.log("e"));
});
console.log("f");

Our run printed a, f, c, e, b, d. Here is why:

  1. a and f are synchronous, so they run first.
  2. The stack is empty, so microtasks run: c, then the new microtask e, in the same round.
  3. Now one task: timer b, which was queued first.
  4. Then the next task: timer d, which was queued during the microtask.

Common mistakes

  • Thinking setTimeout is exact. The delay is only a minimum.
  • Thinking async means another thread. Async code still runs on the main thread between awaits.
  • Using sleeps to fix ordering. Waiting on the actual condition is far more reliable, which also applies to flaky tests.
  • Using forEach with await. It does not wait between items. See JavaScript array methods.
  • Doing heavy synchronous work in a server handler. One request can delay every other request.

Final thoughts

Remember the core rule: run the stack until it is empty, run all microtasks, then run one task, and repeat. Everything else follows from it. To make it stick, write your own version of the quiz above, predict the output on paper, and then run it. Getting one wrong and understanding why will teach you more than any diagram.

Frequently asked questions

What is the event loop in JavaScript?

It is the mechanism that runs queued callbacks when the call stack is empty. It lets single-threaded JavaScript handle timers, input and network responses without blocking.

What is the difference between a microtask and a task?

Microtasks, such as promise callbacks, all run as soon as the stack empties. Tasks, such as timers, run one at a time, with microtasks drained after each.

Why does setTimeout with 0 not run immediately?

Its callback must wait for a task turn. All synchronous code and microtasks run first, and the delay is a minimum rather than an exact time.

Is JavaScript single-threaded?

Your main JavaScript code runs on one thread. Browsers and Node.js use other threads for some background work, and workers let you run code in parallel.

Does await block the event loop?

No. await pauses only that async function, and other code can run in the meantime. Long synchronous code before or after it can still block the loop, though.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →