This is a cross-post of the original article.
Read the full version, including the interactive visualizations, on audreyhal.com.
Quick quiz. What does this print, and in what order?
console.log("start");
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise1"));
Promise.resolve().then(() => console.log("promise2"));
console.log("end");
The answer is:
start
end
promise1
promise2
timeout
If that's not what you guessed, don't worry. Most people don't get it right the first time.
By the end of this post, you'll know exactly why it happens.
The Four Pieces, at a Glance
"The event loop" gets used as a catch-all term. But it's really just one part of a small system with four pieces:
The call stack: where your code runs, one step at a time
Web APIs: browser tools (like timers and network requests) that can do work outside your code
Two queues: waiting lines for work that's finished and ready to run
The
Discussion
Get the discussion rolling
A single comment can start something great.