What's The Event Loop
Javascript is a single threaded runtime: it has one call stack and one memory heap, executing code in order and must finish a piece of code before moving on to the next.
How does it do async?
It relies on something called the event loop.
Chrome runs on V8: a JS engine. If you take a look at the source code, things like setTimeout() does not exist.
Instead, common async functions such as setTimeout() and fetch() come from WebAPI.
console.log("first");
setTimeout(() => {
console.log("second");
}, 1000);
console.log("third");
When this is run, this is the output.
first;
third;
undefined; // only if run in chrome snippets
second;
- console.log("first") is on the stack first, so it gets popped off and runs.
- setTimeout() is next, and is handed over to WebAPI to run in the background. (WebAPI is written in C++ btw)
- it moves on, and console.log("third") runs.
- once the setTimeout is processed by the WebAPI, it's returned to something called the callback queue
- The callback queue is processed when there's nothing left in the stack, and the oldest item is passed to the top of the stack. (this is why a setTimeout() with no delay will not run in place.)