Google Chrome在alert()功能上的不可预知的行为 [英] Google Chrome's unpredictable behaviour on alert() function

查看:300
本文介绍了Google Chrome在alert()功能上的不可预知的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如您看到 alert()这样的阻止类功能在Google Chrome的事件队列中填充 setTimeout时,其输出不按顺序 ()函数,基于此代码。

  for(var i = 1; i <= 6; (函数(){alert(index)},100); 

(函数(索引){

setTimeout(

)) (一世);





  • 为什么?

  • 是否被视为Google Chrome的错误?



这应该有一个解释。

解决方案

一般来说,期望在任何给定的时刻精度),只有一个执行时隙,任何事件(如 setTimeout 回调)都应该发生在这个时刻队列。这似乎是OP的期望。



然而,没有什么东西需要浏览器以这种方式工作,并且事情如何进行调度的实际情况要复杂得多,也因浏览器而异。



所以,最好的办法是不要依赖任何两个事件的相对顺序,不管你认为他们应该有多可预测。

我在这里有一篇关于定时器特有性质的博客文章,以及我对他们的类似挫折: https://web.archive.org/web/20151029223348/http:/ /blog.getify.com/on-the-nature-of-timers


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

这篇关于Google Chrome在alert()功能上的不可预知的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆