Mehdi Raash Mehdi Raash - 5 months ago 45
Javascript Question

Google Chrome's unpredictable behaviour on alert() function

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++) {


setTimeout(function() { alert(index) }, 100);



  • 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: