As other also noted, setTimeout() has a minimum timeout of 4ms.
More importantly though, even if it had a real time-out of 0ms, it wouldn't fire first either. That's because Javascript is single-threaded (disregarding web-workers).
alert(2)
fires last because anything set in setTimeout() will only fire after the current Javascript execution is done. In other words: setTimeout() actions are placed at the end of the execution stack.
So the current function execution will finish first (running the alert(1)
) and only then the alert(2)
gets executed.
That's also the reason that setTimeout
only guarantees that the code within it is executed after the specified time, not at the exact time.
See http://ejohn.org/blog/how-javascript-timers-work/ for a great overview.