阅读 186

定时器(setTimeout/setInterval)最小延迟的问题

HTML5规范中规定

If timeout is less than 0, then set timeout to 0.
If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.

也就是说,定时器在嵌套层级超过5层时,最小延迟变为4ms,如下代码,层级一直嵌套

function cb() { f(); setTimeout(cb, 0); }
setTimeout(cb, 0);
复制代码
setInterval(f, 0);
复制代码

实际在浏览器的实现中,不同浏览器规定的嵌套层级和最小延迟都有所不同:在Chrome和Firefox中定时器的第5次调用被阻了,Safari是在第6次,Edge是在第3次;Chrome的Blink最小延迟是1ms

// https://chromium.googlesource.com/chromium/blink/+/master/Source/core/frame/DOMTimer.cpp
if (!(after >= 1 && after <= TIMEOUT_MAX))
  after = 1; // schedule on next tick, follows browser behavior
复制代码

在Node中也不一样,没有说嵌套层级,就是最小延迟是1ms

When delay is larger than 2147483647 or less than 1, the delay will be set to 1.

最后

欢迎关注我的微博@狂刀二