As you can see a blocking kind of function like alert() produce its output not in order when is filled in event queue of Google Chrome's by setTimeout() function, based on this code.
for (var i = 1; i <= 6; i++) {
(function(index){
setTimeout(function() { alert(index) }, 100);
})(i);
}
- Why is that?
- Is it considered as a Google Chrome's bug?
There should be an explanation for that.
Generally, it makes sorta sense to expect that at any given moment (say, in millisecond precision), there's only one slot of execution, and any events (like setTimeout
callbacks) that should happen at that moment should all be in a single queue. That seems to be the expectation of the OP here.
However, there's nothing that requires browsers to work this way, and the reality of how things get scheduled is much more complex, and also varies by browser.
So, best bet is to never rely on the relative ordering of any two events, no matter how much you think they should be predictable.
I have an archived blog post here about the peculiar nature of timers and my (similar) frustrations with them: https://web.archive.org/web/20151029223348/http://blog.getify.com/on-the-nature-of-timers