setTimeout/setInterval delay数值过大问题

delay 参数将转换为带符号的32位整数,这有效地将延迟限制为 2147483647 ms(约 24.8 天)

2147483647 === Math.pow(2, 31) - 1 === parseInt('01111111111111111111111111111111', 2)

在nodejs和浏览器中执行的情况有所差异

Nodejs 中

setInterval(callback, delay[, ...args])
setTimeout(callback, delay[, ...args])

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

行为统一!当 delay 大于 2147483647 时,将会被设置为 1。-- Here

// 下述 delay 都为 1
setInterval(() => {
	console.log(+new Date())
}, 3333333000)

setInterval(() => {
	console.log(+new Date())
}, 9999999000)

setInterval(() => {
	console.log(+new Date())
}, 2147483647 + 1)

浏览器

  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.

关注第四点:如果超时是Infinity值,非数字(NaN)值或负值,则将超时设置为零。Here

通过测试规律发现,浏览器中超过32位的,会自动截取32位,如果第32为1,即负数,则将超设置为0;否则会将后32位,转化为相应毫秒值进行执行!

parseInt('0000000000000000000101110111000', 2) === 3000

上述为 3000 ms

示例1:将第32位变为1

setTimeout(() => {
	console.log(+new Date())
}, parseInt('1000000000000000000101110111000', 2))  // 立即执行

示例1:将第32保持0,增加第33位为1,让数字溢出

setTimeout(() => {
	console.log(+new Date())
}, parseInt('10000000000000000000101110111000', 2))  // 3000ms后执行

其他: 现代浏览器中,setTimeout()/setInterval()

  • Timeouts throttled to ≥ 4ms
  • Timeouts in inactive tabs throttled to ≥ 1000ms

参考地址

  • https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
  • https://nodejs.org/api/timers.html#timers_settimeout_callback_delay_args
  • https://www.w3.org/TR/2011/WD-html5-20110525/timers.html
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋飛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值