javascript - setTimeout(fun) 和 setTimeout(fun,4) 之间有区别吗

标签 javascript html settimeout

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:

  1. Let timeout be the second argument to the method, or zero if the argument was omitted.

  2. Apply the ToString() abstract operation to timeout, and let timeout be the result. [ECMA262]

  3. Apply the ToNumber() abstract operation to timeout, and let timeout be the result. [ECMA262]

  4. If timeout is an Infinity value, a Not-a-Number (NaN) value, or negative, let timeout be zero.

  5. Round timeout down to the nearest integer, and let timeout be the result.

  6. Return timeout.

关于javascript - setTimeout(fun) 和 setTimeout(fun,4) 之间有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21050196/

相关文章:

javascript - 如何用纯javascript控制奇观呈现?

javascript - jQuery Datepicker 显示当前日期

javascript - 使用 JQuery 逐个添加元素

javascript - 如何从 setInterval 函数返回值?

jquery - 如何在 "X"秒后调用 jquery 函数

javascript - 使用 JavaScript 创建 16x16 网格

javascript - AngularJS 允许 POST 或 PUT 到 Web 服务跨域?

html - 如何修复 div 的边距

html - 嵌套 SCSS 并定位父级

javascript - api block 被调用 2 次,导致渲染组件两次,但条件得到正确检查