Javascript is single-threaded, that mean it runs only one instruction at a time, sequentially.
The event system, like in many other languages and library, is handle by an event loop. The event loop is basically a loop, which on each iteration check for message in the queue, and dispatch events.
In javascript (as in mot of languages implementing this pattern), the event loop is called when the stack is empty, that is to say, when all functions have returns, in other word, at the end of the program code.
Your "real" program look something like this behind the scene :
var run = true, i = 0;
setTimeout(function(){ run = false; }, 1);
while(run){ i++; }
while(true) {
/*
* check for new messages in the queue and dispatch
* events if there are some
*/
processEvents();
}
So the message from the clock saying timeout is over is never processed.
More info on the event loop on :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop
Of course it is a bit more complex, check here those examples : Is JavaScript guaranteed to be single-threaded? (tl;dr: In some browser engines, some external events are not dependent on the event loop and are immediately fired when they occur, preempting the current task. But this is not the case with setTimeout, which just add a message to the queue and never fires immediately.)
var run = true, i = 0; function loop() { i++; if (run) setTimeout(loop, 0); }; setTimeout(function() { run = false }, 1); loop();
– Herren4ms
per definition. So you waste a lot of time in the timeout and function calls. – Binion