setTimeout 的行为有点令人困惑, 我读过的所有资源都表明,当没有指定延迟时,任务将被附加到队列末尾,并在解释器无事可做时执行(空队列?)。 但是,请看以下示例:
setTimeout(function() { console.log('without delay!'); })
setTimeout(function () { console.log('with delay'); }, 1000);
var start = Date.now();
while (Date.now() < start + 3000) {} // block for 3 seconds
console.log('After wait');
根据上述前提,输出将是:
After wait
with delay
without delay
但是,输出是(在 Chrome 和 Firefox 中测试):
After wait
without delay
with delay
(注意,当调用setTimeout(fn,1000)
时,当解释器在1秒后空闲时,fn就会被执行,这可以是1秒,5秒,如果口译员仍然忙碌,甚至永远。)
前面的示例让我推断出 setTimeout(fn)
、setTimeout(fn,0)
和 setTimeout(fn, 4)
(4ms是HTML5中的最小延迟),因为没有延迟的函数先于延迟1秒的函数执行完毕。(两者都已准备好执行)
所以我的问题是它们是否等效? (在 HTML5 中)。
最佳答案
没有超时相当于0,0相当于4,根据W3 specification for timers :
http://www.w3.org/TR/2011/WD-html5-20110525/timers.html#dom-windowtimers-settimeout :
...
4. Get the timeout, and let timeout be the result.
5. If the currently running task is a task that was created by the setTimeout() method, and timeout is less than 4, then increase timeout to 4.
http://www.w3.org/TR/2011/WD-html5-20110525/timers.html#get-the-timeout :
When the above methods are to get the timeout, they must run the following steps:
Let timeout be the second argument to the method, or zero if the argument was omitted.
Apply the ToString() abstract operation to timeout, and let timeout be the result. [ECMA262]
Apply the ToNumber() abstract operation to timeout, and let timeout be the result. [ECMA262]
If timeout is an Infinity value, a Not-a-Number (NaN) value, or negative, let timeout be zero.
Round timeout down to the nearest integer, and let timeout be the result.
Return timeout.
关于javascript - setTimeout(fun) 和 setTimeout(fun,4) 之间有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21050196/