具有相同间隔的多个setTimeout()函数的执行顺序 [英] Execution order of multiple setTimeout() functions with same interval
问题描述
考虑以下Javascript代码:
Consider the following Javascript code:
function(){
setTimeout(function() {
$("#output").append(" one ");
}, 1000);
setTimeout(function() {
$("#output").append(" two ");
}, 1000);
}
您还可以在 jsfiddle 。
我可以确定 #output
的值总是一二
,按此顺序?通常,我会像这样处理这个问题:
Can I be sure that the value of #output
is always "one two"
, in that order? Usually, I would handle this problem like this:
function(){
setTimeout(function() {
$("#output").append(" one ");
$("#output").append(" two ");
}, 1000));
}
但我无法这样做,因为我从服务器获取消息告诉我要执行哪个函数(在这个例子中附加one
或追加two
),我有执行时有一点延迟。
But I can not do it that way because I get messages from a server which tells me which function to execute (in this example append "one"
or append "two"
), which I have to execute with a small delay.
我已经在Internet Explorer 9,Firefox 14,Chrome 20和Opera 12中测试了这段代码,输出总是one two
,但我能确定这种情况总是如此吗?
I already tested this code in Internet Explorer 9, Firefox 14, Chrome 20 and Opera 12, and the output was always "one two"
, but can I be sure that this will always be the case?
推荐答案
规范是此处。
我对 setTimeout
7.3节中的步骤8的解释是执行顺序 保证。
My interpretation of setTimeout
step 8 in section 7.3 is that the execution order is supposed to be guaranteed.
然而,我调查了这个问题,因为当窗口最小化然后在Chrome中最大化时,我发现在来自外部资源的事件中设置了超时(像websockets或webworkers)正在以错误的顺序执行。我认为这是一个浏览器错误,很快就会修复。
However, I investigated this issue because when the window is minimized and then maximised in Chrome, I was finding that timeouts set in events coming from external sources (like websockets or webworkers) were being executed in the wrong order. I assume this is a browser bug and will hopefully be fixed soon.
这篇关于具有相同间隔的多个setTimeout()函数的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!