I know messages come into call stack from the queue when call stack is empty. Wouldn't it be better though, if event loop could push messages from queue directly to call stack without waiting? What reasons are behind this behavior? If the event loop would push a message at an exact time we could always rely on function such as setTimeout etc.
setTimeout(() => console.log("I want to be logged for 10ms, but I will never be :("), 10);
// some blocking operations
for(let i = 0; i < 500000000; i++){
Math.random() * 2 + 2 - 3;
}
console.log("I'll be logged first lol");
It'll probably never be changed due to consistency reason but I'm still curious. Maybe I'm not seeing something, and there is the serious technical reason behind the concept of waiting for an empty stack. Do you have access to some articles about architectural decisions in JS, or maybe you know fundamental examples when this behavior is necessary? There are many articles about how JS works, but I couldn't find anything like "Why event loop works exactly that way". Any help would be greatly appreciated.
setTimeoutguarantees its code isn't run until 10ms have passed. Not exactly 10ms after it is read. You should consider your question from a different angle: what does blocking operation means? ;) In order to make ticks/EventLoop/timeouts/whatever work the way you're thinking, it would indeed require multiple threads, i.e. deferring the processing control to a higher authority (like the OS). So my guess is it was implemented this way to make the necessary event-driven programming without the heavy artillery of thread-handling logic and most of its pitfalls. And to build it in 10 days.