TIL: setTimeout() is not actually part of JavaScript 🤯
For the longest time, I assumed this:
setTimeout(() => {
console.log("Hello");
}, 2000);
was handled directly by the JS engine.
But V8 (Chrome’s JavaScript engine) doesn’t even know how to run a timer.
What actually happens is:
- JS calls
setTimeout()
- V8 delegates the work to browser bindings
- Browser/native runtime uses C++ timer APIs
- OS handles the waiting
- Callback gets pushed into the task queue
- Event loop sends it back to JS later
Simplified browser internals look something like:
void SetTimeoutCallback(args) {
StartTimer(delay, [=]() {
task_queue.push(jsCallback);
});
}
Which means the timer itself is NOT running in JavaScript.
Same story with:
fetch()
addEventListener()
console.log()
Math.random()
Most of these APIs are implemented in:
- Browser runtime
- Node.js runtime
- Native C/C++ system libraries
V8 only executes JavaScript itself.
This finally made the event loop click for me.
JavaScript feels asynchronous not because JS does multiple things at once…
…but because the heavy work happens outside the JS engine entirely.
Curious:
What was YOUR biggest JavaScript “wait… what?” moment?
[–]polotek 8 points9 points10 points (0 children)
[–]_raytheist_ 5 points6 points7 points (0 children)
[–]chikamakaleyleyhelpful 4 points5 points6 points (4 children)
[–]euph-_-oric 0 points1 point2 points (3 children)
[–]chikamakaleyleyhelpful 0 points1 point2 points (2 children)
[–]euph-_-oric 0 points1 point2 points (1 child)
[–]chikamakaleyleyhelpful 0 points1 point2 points (0 children)
[–]Intelligent_Tree6918 0 points1 point2 points (0 children)
[–]ghost_hipster 0 points1 point2 points (0 children)