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

 (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

    链接地址: http://www.djcxy.com/p/51924.html

    上一篇: SAP .NET连接器

    下一篇: Google Chrome在alert()功能上的不可预知的行为