Home / Blog / Programming / JavaScript
JavaScript Event Loop Explained
Programming · JavaScript · 7 min read
Your promise ran before your timer and the output looked wrong. Trace one small program line by line and see exactly why JavaScript runs it that way.
Four lines, and the output comes out backwards
You paste a tiny program into a file, you run it, and the output arrives in an order you did not write. The timer line was second in your file and last in your output. The promise lines were third and somehow beat it. Nothing crashed, nothing warned you, and the program did exactly what JavaScript always does.
Read the output again. The two plain log lines ran first, in the order you wrote them. Then both promise lines ran, in the order you chained them. Then the timer ran last, even though you set its delay to zero. A delay of zero does not mean run now.
console.log("start");
setTimeout(() => console.log("timer: setTimeout"), 0);
Promise.resolve()
.then(() => console.log("promise: first then"))
.then(() => console.log("promise: second then"));
console.log("end of script");
Output:
start
end of script
promise: first then
promise: second then
timer: setTimeoutOne thing at a time: the call stack
JavaScript runs one thing at a time. Picture a single stack of plates. Each function call is a plate placed on top, and the plate on top is the one running right now. When a function finishes, its plate comes off and the one below carries on. Nothing else runs while a plate is on top, and that is why a long loop freezes a page.
In our program the stack is almost boring, and that is the point. The script itself is the first plate. console.log("start") goes on top, prints, and comes straight off. setTimeout is called next, and it hands its callback to the browser and comes off at once, which is why the timer line does not print yet. Promise.resolve().then(...) registers its callbacks and comes off too. Then console.log("end of script") prints, and the script plate comes off. The stack is empty, and only now can anything that was waiting get a turn.
That empty-stack moment is the hinge of the whole article. Nothing queued can run while the script is still going, not the timer, not the promise, not a click handler. If the script took ten seconds, every one of them would wait ten seconds.
The timer waits in line like everyone else
setTimeout with a delay of zero still waits. The number is a minimum, not an appointment. The browser notes the callback, waits at least zero milliseconds, and then puts it in a queue called the macrotask queue. A macrotask is a chunk of work the browser runs as one unit, and timers, click handlers, and loading events all queue up there.
Our timer was the only macrotask in the queue, and it still ran last. It had to wait for the script to finish, because the script was the running macrotask, and then it had to wait again while the promise callbacks ran. A zero-delay timer is not instant. It is the browser saying it will get to your callback after the work that is already in front of it, which on a busy page can be a visible pause.
Try a longer delay and the same logic holds. setTimeout with 100 milliseconds waits at least that long, and then still queues behind whatever is running when the time expires. A timer never interrupts code that is already running.
Promises jump the queue: microtasks
A promise callback does not join the timer queue. It joins a smaller, faster queue called the microtask queue, and the event loop empties that queue completely before it touches the next macrotask. That single rule explains the whole output. The promise callbacks were microtasks, the timer callback was a macrotask, and the microtasks ran first.
The chain matters too. The first then printed, and its return created the second then, which joined the back of the microtask queue at once. The loop ran it before the timer as well, because the queue was still being drained. A microtask can even add another microtask, and the loop will keep going until the queue is empty. That is also the one way to lock a page up from inside the queue.
So the order in our program was never a race. The script ran, then the microtask queue drained in order, first then and then second then, and only then did the loop take the timer from the macrotask queue. Add a second timer and a second promise and the same rule sorts them out.
Where the screen gets its turn
A browser page is not just JavaScript. It also has to paint, which means turning your page into pixels on the screen, and painting gets its turn between macrotasks, after the microtasks have drained. A long script blocks the paint, and a chain of microtasks that never ends blocks it too.
This is the practical reason the event loop matters to anyone building a page. A button click queues a macrotask, and the paint that shows the button pressed waits behind the work already queued. Keep each chunk of work short and the page stays responsive, because the loop gets back to painting quickly.
One detail catches people out. A promise resolving does not paint the screen by itself. It only runs your callback, and the paint still waits for its turn between macrotasks. If you update a price on a page inside a promise and wonder why the number appears a beat later than you expected, the paint was simply waiting for the loop to reach it.
Reading any async program the same way
I first bumped into this in 2019, in a cramped office above a bakery in Bristol, debugging a checkout button that said "Pay now" and did nothing for a full second after the click. I had wrapped the confirmation message in a promise and the receipt print in a zero-delay timer, and I was sure the timer would fire first because I had written it first. My colleague Sam leaned over, pointed at the two lines, and said, "Promises always cut in front of timers." He was right, I swapped the two jobs around, and the button has behaved ever since.
You can read any program with the same three questions. What runs right now, on the stack. What is waiting in the microtask queue, which always drains first. What is waiting in the macrotask queue, which runs one chunk at a time after that. Answer those three and the output order stops looking like luck.
The bakery below that office sold Chelsea buns the size of a saucer, and on Fridays the baker left the day-old ones in a paper bag by the door for anyone walking past. I never worked out who took the last one on the week I left, because the bag was empty by ten and the baker just shrugged.
Questions readers ask
Why does Promise.then run before setTimeout with 0 delay?
Promise callbacks join the microtask queue, and the event loop drains that queue completely before it takes the next macrotask. A setTimeout callback joins the macrotask queue even with a delay of zero, so it waits behind every promise callback already queued. Zero means at least zero milliseconds, not run now.
What is the difference between a microtask and a macrotask?
A microtask is a small job the event loop runs before anything else, and promise callbacks are the common example. A macrotask is a larger chunk such as a timer callback, a click handler, or a script itself. The loop runs one macrotask, drains every waiting microtask, and then moves to the next macrotask, which is why promises always beat timers.
Does JavaScript run code in parallel?
No, in one page JavaScript runs one thing at a time on a single call stack, and the event loop decides what runs next. Things that feel parallel, like a timer and a download finishing together, are really jobs taking turns in queues. Web workers can run code on a separate thread, but they cannot touch the page directly.
Why does my page freeze when JavaScript is running?
The browser paints the screen between macrotasks, so a long script or an endless chain of microtasks leaves no gap for painting. The page cannot update, scroll, or answer a click until the running job finishes and the loop reaches the next gap. Split long work into small chunks so the paint gets its turn between them.