All 28 lessons ▾
Inside JavaScript · Lesson 15 of 28
The Event Loop, From Scratch
So how does single-threaded JavaScript wait for timers, clicks, and servers, all at once, without freezing? So let's meet the event loop.
A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.
Got a doubt? Ask in the comments under the video.Subscribe
- One call stack, and no timer of its own
- Web APIs: timers, DOM, fetch, storage, console
- Finished async callbacks wait in a queue
- The event loop pushes them when the stack is empty
- Microtasks (promises) go before the callback queue
- Even setTimeout 0 waits for an empty stack
Part 1The browser's superpowers
So today is a big one. The event loop. Everyone has heard this word. But very few people can explain it properly. So by the end of this episode, you will. Now let's start with a surprising fact. The call stack has no timer. It simply runs whatever comes into it, immediately. Remember from episode eleven? JavaScript waits for nobody. So if JavaScript can't wait, who does the waiting? Let's find out.
So your browser is much more than a JavaScript engine. The engine has the call stack, where your code runs. But the browser around it has superpowers. A timer, for setTimeout. The DOM, which is your web page. The power to talk to servers, with fetch. Local storage, to save data. Even Bluetooth, and your location. And even the console! Now none of these are part of JavaScript. They belong to the browser, and they're called Web APIs. So how does your code reach them? Through the global object, window. That's why you can write setTimeout, instead of window.setTimeout. Same thing. The window part is just implied.
Part 2Follow one timer
Now let's follow a single setTimeout, all the way, and see exactly who does what.
1console.log("start");2setTimeout(function cb() {3 console.log("timer");4}, 5000);5console.log("end");start end timer
A global execution context is pushed. Line one calls console.log, which uses the console Web API, and start appears. Line two calls setTimeout, which uses the timer Web API. It registers the callback, cb, and starts a five second timer, outside the engine. And JavaScript moves on, right away. Line five prints end. The program is over, so Global goes, and the call stack is empty. So meanwhile, the timer keeps ticking. Five seconds later, it's done. Now cb needs to run, and to run, it must get onto the call stack. Here it comes. cb is pushed, line three runs, and timer is printed. Then cb is popped. But now how exactly did cb travel from the timer to the call stack? Let's see.
So here's the full picture. When setTimeout runs, cb is registered in the Web APIs, with its timer. Now when the timer expires, cb doesn't jump straight onto the call stack. It goes into a waiting line, called the callback queue. And now, the hero of today. The event loop. It has just one job. It keeps checking. Is the call stack empty? And is something waiting in the callback queue? If yes, it takes the first function from the queue, and pushes it onto the call stack. That's all it does! Simple. So the event loop is like a gatekeeper. It lets callbacks in, one at a time, only when the stack is free.
So remember this. JavaScript runs your code on the call stack. The browser does the waiting, in its Web APIs. Finished callbacks line up in the callback queue. And the event loop moves them onto the call stack, but only when the stack is empty. Now I'll say it once more in one line. Web APIs wait, the queue holds, the event loop delivers.
Part 3Clicks take the same road
Now timers aren't special. Every async callback in the browser takes the same road. So let's see a click.
1console.log("Start");2 3btn.addEventListener("click", function cb() {4 console.log("Callback");5});6 7console.log("End");Line one prints Start. Line three registers cb in the Web APIs, attached to the click event. Line seven prints End, and Global leaves the call stack. But cb stays in the Web APIs, waiting. Maybe for a second, maybe forever, until the user clicks, or you remove the listener. Now the user clicks. cb moves into the callback queue. The event loop sees an empty call stack, and pushes cb onto it. And Callback is printed. So same road as the timer. Web API, then the queue, then the event loop, then the stack.
Now, why do we even need a queue? So imagine the user clicks the button six times, really fast. That's six callbacks, all ready. They can't all run at once, because there's only one call stack. So they wait in the callback queue, in order. The event loop takes the first one, pushes it, it runs, and it's popped. Then the next one. Then the next. Six clicks, six callbacks, one by one. First in, first out. So that's why it's a queue.
Part 4fetch and the VIP queue
Now let's make it trickier. What happens when a timer and a network request are ready at the same time?
1console.log("Start");2 3setTimeout(function cbT() {4 console.log("CB Timeout");5}, 5000);6 7fetch("https://api.movies.com").then(function cbF() {8 console.log("CB Fetch");9});10 11// ...a million lines, taking 6 seconds12console.log("End");Start End CB Fetch CB Timeout
So fetch asks a server for data, and gives back a promise. And .then registers cbF, to run when the data arrives. Line one logs Start, as always. Line three registers cbT, with a five second timer. Line seven sends the request, and registers cbF. Now say the server answers in two seconds. Then a million lines of code run, taking six seconds. So when line twelve finally prints End, the data is back, and the timer is done too. Both callbacks are ready! So which one runs first? cbT was registered first, so cbT? No! First comes CB Fetch, and then CB Timeout. Why?
Because there are two queues, not one. When the stack is empty, a callback from a promise, like cbF, doesn't go to the normal queue. It goes to a special one, called the microtask queue. And cbT goes to the callback queue, as usual. Now here's the rule. The microtask queue has higher priority. So the event loop first empties the whole microtask queue, and only then picks from the callback queue. So cbF runs first, even though both were ready. Think of it as the VIP line at an airport.
So remember this. Callbacks from promises, and from something called a mutation observer, which watches the DOM for changes, go into the microtask queue. Everything else, timers, clicks, and other events, goes into the callback queue, which is also called the task queue. And microtasks always go first. Now one warning, though. If microtasks keep creating more microtasks, the callback queue never gets a turn. That's called starvation. It's rare, but now you know the name.
Part 5Four questions people ask
So before we wrap up, here are four questions people often ask about the event loop. These are important, so let's answer them quickly.
One. When does the event loop start? It never stops. It's an almost endless loop, always checking. Two. Do the callbacks of map, filter, and reduce go through the Web APIs? No! Those are synchronous callbacks. They run right away, on the call stack. Only async callbacks take this journey. Three. Do event listeners stay in the Web APIs? Yes. For as long as they're attached, which is why we remove them when we're done. And four. What if setTimeout's delay is zero? The callback still has to wait in the queue, until the call stack is empty. So even zero isn't really zero. Now we'll dig into that in episode seventeen.
1console.log("1");2setTimeout(function () {3 console.log("2");4}, 0);5Promise.resolve().then(function () {6 console.log("3");7});8console.log("4");What's the order?
Show the answer
So one and four come first, because they're plain synchronous code. Then the stack is empty, and two callbacks are waiting. The promise callback is a microtask, so three goes first. And then the timer, two. So one, four, three, two. If you got that, you understand the event loop better than most developers. Seriously, well done!
Did the one, four, three, two quiz trick you?
Answer in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.