setTimeout 最小延时

36 阅读1分钟

常听同事说setTimeout自小延迟是4ms,其实这样的说法并不全对。

  • 浏览器端

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

当延迟小于0,会被设为0;
当嵌套使用并且层级大于5时(浏览器实现的大于等于5),会被设为4ms。

  • node端
    当延迟小于1或大于2**31 - 1时,会被设为1ms。 node:v16.17.0`部分源码 image.png