Explain the JavaScript Event Loop: How One Thread Handles Everything
# Explain the JavaScript Event Loop: How One Thread Handles Everything
JavaScript is single-threaded — it can only run one piece of code at a time. Yet a JavaScript app can fetch data from an API, respond to clicks, run timers, and update the screen, all seemingly at once. How does one thread do all of that without freezing?
The answer is the **event loop**. It is the mechanism that lets JavaScript appear concurrent while staying single-threaded, and once you understand it, a whole class of confusing behaviour — timers firing late, promises resolving in a surprising order, a page freezing during a heavy calculation — finally makes sense.
At Ovlyc, the event loop is one of the first concepts we walk through with developers on a new project, because it shapes how we write every asynchronous feature: API calls, file uploads, background jobs, and real-time updates.
## The Problem the Event Loop Solves
Imagine a web page that fetches user data from a server. The request takes 800 milliseconds. If JavaScript simply waited for the response, the whole page would freeze for 800 milliseconds — no clicks, no scrolling, no typing. Users would notice immediately.
Instead, JavaScript hands the waiting to something else. It starts the request, moves on to other work, and runs a callback when the response arrives. The event loop is the coordinator that makes this handoff work.
## The Four Parts of the Model
The runtime around JavaScript — the browser or Node.js — has four pieces that work together:
**1. The call stack**
The stack is where code actually runs, one function at a time. When a function is called, it is pushed onto the stack; when it returns, it is popped off. The stack is strictly first-in, last-out, and it is always the thing that is executing right now.
**2. Web APIs (browser) or C++ APIs (Node.js)**
These are features provided by the environment, not by the JavaScript language itself: `setTimeout`, `fetch`, DOM events, file system access. When your code calls one of these, the runtime takes over the waiting in the background, outside the stack.
**3. The callback queue (also called the task queue)**
When a background operation finishes, its callback is placed in a queue, waiting its turn. Callbacks sit here until the stack is empty.
**4. The event loop**
A simple, endlessly repeating check: *is the call stack empty?* If yes, take the oldest callback from the queue and push it onto the stack so it can run. If no, wait.
That is the whole loop. It never runs your code directly — it only decides *when* queued work gets its turn on the stack.
## A Walkthrough: What Actually Happens
```js
console.log("Start");
setTimeout(() => {
console.log("Timer finished");
}, 0);
console.log("End");
```
You might expect "Start", "Timer finished", "End". The actual output is:
```
Start
End
Timer finished
```
Even with a delay of `0`, the timer callback does not run immediately. Here is why, step by step:
1. `console.log("Start")` runs on the stack and prints immediately.
2. `setTimeout` is called. The runtime starts a timer in the background and the call returns at once — nothing waits.
3. `console.log("End")` runs and prints.
4. The main script finishes, so the stack becomes empty.
5. Meanwhile the timer has finished, and its callback is sitting in the callback queue.
6. The event loop sees the empty stack, takes the callback from the queue, and pushes it onto the stack. "Timer finished" prints.
The `0` in `setTimeout(..., 0)` does not mean "run now". It means "run as soon as possible — after the current stack clears". That distinction is the event loop in one sentence.
## Timers, Network Requests, and User Events
The same pattern applies to every asynchronous operation:
```js
console.log("Fetching data...");
fetch("https://api.example.com/orders")
.then((response) => response.json())
.then((orders) => {
console.log("Orders loaded:", orders.length);
});
console.log("UI stays responsive");
```
`fetch` starts the network request in the background and returns immediately. The code after it keeps running, the user can keep clicking, and the `.then()` callback is queued when the response arrives. Nothing blocks.
User events work the same way. A click handler is not running all the time, waiting for a click — it is registered once, and when the user clicks, the runtime places the handler in the queue. The event loop picks it up when the stack is free. This is why a long-running function can make a page feel unresponsive: while it occupies the stack, no click handler can run, no matter how many times the user clicks.
## Blocking the Loop: The One Thing That Breaks Everything
Because there is only one stack, any code that runs for a long time blocks everything behind it:
```js
// This blocks the event loop for 3 seconds
const start = Date.now();
while (Date.now() - start < 3000) {
// busy waiting — the stack never clears
}
console.log("Done waiting");
```
During those three seconds, no timer fires, no network callback runs, and no click is handled. The queue grows, but the loop cannot deliver anything because the stack is never empty.
This is the most common performance bug in JavaScript applications. In practice it shows up as:
- A page that freezes while a large list is rendered or a big file is processed.
- A server that stops answering requests while one request does heavy work.
- Timers that fire much later than their scheduled time, because the stack was busy when they expired.
The fixes all follow the same principle — keep the stack clear:
- **Break big jobs into chunks** with `setTimeout` or `requestAnimationFrame`, so the loop gets a chance to run other work between chunks.
- **Move heavy work off the main thread** with Web Workers in the browser or worker threads in Node.js.
- **Use streaming and pagination** instead of loading and processing huge datasets in one go.
## Microtasks: The Priority Lane
Not all queued work is equal. Promise callbacks do not go into the regular callback queue — they go into a separate **microtask queue**, which the event loop empties *before* every regular task. In practice this means promise callbacks always run before timer callbacks, even if the timer was scheduled first:
```js
setTimeout(() => console.log("Timer"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("Sync code");
// Output:
// Sync code
// Promise
// Timer
```
The order is: synchronous code first, then all pending microtasks, then the next regular task. This ordering is worth knowing, but the details of microtasks versus macrotasks deserve their own deep dive — and that is exactly what the next article in this series covers.
## The Event Loop in Node.js
The same idea powers Node.js, with one difference: the loop there has *phases* — timers, pending callbacks, I/O polling, `setImmediate`, and close callbacks — that it cycles through in order. The principle is identical: the stack runs your code, background work happens outside it, and the loop delivers finished work when the stack is free. That is how a single Node.js process can serve thousands of concurrent connections without a thread per request.
We will look at the Node.js loop phases in detail later in this series, when we cover `libuv` and non-blocking I/O.
## Why This Matters When You Build Products
The event loop is not academic trivia — it directly shapes how reliable software feels:
- **Never block the main thread.** If a function can take a long time, split it, defer it, or move it to a worker. A frozen interface is a bug, not a performance detail.
- **Do not trust timer precision.** `setTimeout(fn, 100)` means "no sooner than 100ms", not "exactly at 100ms". If the stack is busy, the callback waits.
- **Keep callbacks short.** Every callback that runs on the stack delays everything behind it. Fast callbacks keep the loop responsive.
- **Understand the order.** Knowing that synchronous code runs first, then microtasks, then timers, removes the surprise from async code — and the surprise is where most async bugs hide.
At Ovlyc, these rules show up in code review constantly. When a dashboard feels sluggish, the first question is usually "what is sitting on the stack?" — and the answer is almost always a long synchronous loop or an unchunked render that should have been handed to the event loop in pieces.
## The Big Picture
The event loop is a simple idea with far-reaching consequences. JavaScript runs one function at a time on a single call stack. Slow operations — timers, network requests, user events — are handled outside the stack by the runtime, and their callbacks wait in a queue. The event loop watches the stack, and whenever it empties, it takes the next callback from the queue and runs it.
That is how one thread stays responsive: it never waits. It starts work, moves on, and lets the loop bring the result back when it is ready.
In the next article, we will go one level deeper into the queues themselves — microtasks versus macrotasks — and explain exactly why promises jump the line ahead of timers.
Related Articles
What Is Node.js? JavaScript Beyond the Browser
Learn what Node.js is, how its V8 engine, libuv, and event loop work, and when to use it for APIs, real-time apps, and full-stack JavaScript.
Execution Context: Where JavaScript Variables Actually Live
Learn how JavaScript execution contexts work — the creation and execution phases, hoisting, the scope chain, closures, and how this is decided.
Microtask vs Macrotask: Why Promises Jump the Queue in JavaScript
Why a zero-delay timer loses to a promise: JavaScript's microtask and macrotask queues explained, with examples of promises, timers, and event-loop starvation.
Call Stack + Heap + Memory: How JavaScript Stores and Runs Your Code
Learn how JavaScript's call stack and heap work together — why recursion overflows, why objects share references, and where memory leaks come from.