Dev.to WebDev 🛠 Dev 👁 0 📖 7 min read

What Is the JavaScript Event Loop? Explained Simply

Originally published on CodingCush. The JavaScript event loop lets JavaScript run one thing at a time, in a single thread, while still handling timers, promises and clicks without freezing the page. Think of a waiter in

What Is the JavaScript Event Loop? Explained Simply

Originally published on CodingCush.

The JavaScript event loop lets JavaScript run one thing at a time, in a single thread, while still handling timers, promises and clicks without freezing the page. Think of a waiter in a small cafe. When a dish needs time in the oven, the waiter serves the next table instead, and serves that dish when the bell rings. In this guide you will learn how the call stack, the task queue and the microtask queue work together, and why a setTimeout of 0 still runs last. All code was run on Node.js v24.22.1, and every output below is the real output.

JavaScript Is Single-Threaded, and That Is Fine

JavaScript has one main thread, so it runs one piece of code at a time. The trick is that JavaScript does not do the waiting itself. When you call setTimeout, fetch data or wait for a click, the browser or Node.js handles the waiting in the background, and the event loop brings each finished job back at the right moment.

The Call Stack: Where Code Runs Right Now

The call stack is the list of functions running right now. When your script starts, it goes on the stack. When it calls a function, that function goes on top, and when it finishes, it comes off the top. It is last in, first out, like a stack of plates:

A function on the stack runs to completion. JavaScript will not pause it halfway, which is why a very long loop can freeze a page. The stack also explains the "Maximum call stack size exceeded" error: a function that keeps calling itself makes the stack grow until the browser gives up. If functions that remember values from their outer scope still feel fuzzy, our guide to JavaScript closures explained with simple examples builds that idea step by step.

The Queue: Where Finished Jobs Wait Their Turn

When a timer finishes, a click happens or a download completes, its callback does not jump straight onto the call stack. It joins a queue, and the event loop checks that queue again and again: if the stack is empty, it takes the first job from the queue and puts it on the stack to run, then repeats. The queue is first in, first out, the opposite of the stack. Clicks work the same way. The browser notes a click at once, but the listener waits in the queue until the stack is clear, which is why a click during a long loop feels delayed. For a refresher, read our guide to JavaScript event listeners explained with practical examples.

Screenshot of MDN's JavaScript execution model page on developer.mozilla.org, which explains the event loop, the stack and the queue

A screenshot of MDN's JavaScript execution model page, which explains the event loop, the stack and the queue.

setTimeout Does Not Mean Run Now

Most beginners get a surprise here: setTimeout with a delay of 0 does not mean "run this now". It means "run this after the current code finishes", because the callback goes to the queue, which is only served when the stack is empty:

console.log("Start");
setTimeout(() => console.log("Timer finished"), 0);
console.log("End");

Output:

Start
End
Timer finished

The timer was set before "End" was logged, but its callback still ran last. That is not a bug, it is the queue doing its job. A delay of 0 is a minimum wait, not an exact time.

Promises and the Microtask Queue: The Fast Lane

Promises have their own smaller queue, the microtask queue. After each task finishes, the event loop empties the whole microtask queue before it takes the next job from the main queue, so a resolved promise always jumps ahead of a waiting timer. Guess the order before you check the output:

console.log("Start");
setTimeout(() => console.log("Timer finished"), 0);
Promise.resolve().then(() => console.log("Promise resolved"));
console.log("End");

Output:

Start
End
Promise resolved
Timer finished

Here is what happened. "Start" logged first, then setTimeout sent its callback to the main queue and the promise sent its callback to the microtask queue. Then "End" logged, because the main script was still running. Once the stack was empty, the loop checked the microtask queue first, so "Promise resolved" printed before "Timer finished". The official MDN guide to the event loop explains this order in detail. For the full picture of promises, our guide to JavaScript promises and async await explained with examples goes from a first .then() to async and await.

Microtasks vs Macrotasks, Side by Side

Callbacks fall into two types: microtasks, the small follow up jobs, and macrotasks, the bigger regular jobs. Microtasks always run before the next macrotask.

Type Examples When it runs
Microtask Promise .then(), queueMicrotask() Right after the current task, before the next macrotask
Macrotask setTimeout, setInterval, clicks, I/O callbacks One at a time, after the microtask queue is empty

A microtask can add another microtask, so a promise chain that never ends can starve the timers. Keep microtask chains short.

What Blocks the Event Loop

Nothing on the stack can be interrupted, so a long loop blocks everything. Timers wait, clicks wait, and the page cannot update until it ends. Here a timer is set for 0 milliseconds, then a busy loop runs for about 300 milliseconds:

console.log("Timer set for 0 ms");
setTimeout(() => console.log("Timer finally ran"), 0);
console.log("Starting a 300 ms busy loop");
const finish = Date.now() + 300;
while (Date.now() < finish) {
  // Nothing else can run while this loop runs.
}
console.log("Busy loop finished");

Output:

Timer set for 0 ms
Starting a 300 ms busy loop
Busy loop finished
Timer finally ran

The timer was ready after 0 milliseconds, but it waited about 300 milliseconds because the stack was busy. That is the real cost of blocking code, so heavy work belongs in small chunks, in a Web Worker, or on the server. The Node.js guide to the event loop, timers and process.nextTick shows the same idea from the server side, where a blocked loop delays every request.

A Longer Walkthrough: Promises, Then Timers, in Order

This example mixes two timers and a promise chain, so you can see the full order:

console.log("Start");
setTimeout(() => console.log("Timer 0 ms"), 0);
setTimeout(() => console.log("Timer 100 ms"), 100);
Promise.resolve()
  .then(() => console.log("First promise"))
  .then(() => console.log("Second promise"));
console.log("End");

Output:

Start
End
First promise
Second promise
Timer 0 ms
Timer 100 ms

"Start" and "End" print first, because they are the main script. Then the microtask queue empties in order: "First promise" prints, and its .then() adds "Second promise", which prints next. Only then does the loop take "Timer 0 ms", and the 100 millisecond timer runs last. If you can trace this without peeking, you understand the event loop well enough for everyday code.

Common Mistakes and Troubleshooting

Thinking setTimeout(..., 0) means run now. It means run after the current stack clears. To run before the next timer, use a promise or queueMicrotask(), not a shorter delay.

Expecting a promise to run before the code after it. A .then() callback also waits until the current script finishes. It only beats timers.

Blocking the loop with a long loop or a huge sort. The page freezes, timers fire late, and clicks feel dead. Split the work into chunks.

Assuming timers fire at exact times. A delay is a minimum, not a promise. A busy stack or a sleeping tab can push a timer later. Never use setTimeout to measure exact time.

Forgetting that fetch and clicks also queue. A fetch response and a button click both join a queue and wait for a clear stack, so check for blocking code first if a click seems slow.

Frequently Asked Questions

Is JavaScript really single-threaded?

Yes, the main thread runs one thing at a time. The browser and Node.js handle waiting and network work in the background, and the event loop brings each finished job back in order.

Why does setTimeout with 0 milliseconds not run at once?

Because its callback goes to the task queue, which is only served when the call stack is empty. The rest of the current script always runs first.

Why do promises run before setTimeout?

Because promise callbacks use the microtask queue, which the event loop empties before taking the next job from the main task queue.

Can the event loop freeze my page?

Yes, if a long loop or heavy calculation stays on the call stack. Nothing else can run until it finishes.

Do I need to learn the event loop to write JavaScript?

You can write simple scripts without it, but you will meet it as soon as timers, promises or clicks behave in an unexpected order.

Conclusion

The event loop is a simple traffic rule, not magic. One thread runs one job at a time on the call stack. Finished timers, clicks and network jobs wait in the queue, promise callbacks wait in the faster microtask queue, and the loop serves them in order whenever the stack is clear. Remember: setTimeout with 0 still waits for the current code, promises beat timers, and long blocking code delays everything.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.