前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >setTimeout/setInterval delay数值过大问题

setTimeout/setInterval delay数值过大问题

作者头像
奋飛
发布2020-05-28 17:06:10
1.1K0
发布2020-05-28 17:06:10
举报
文章被收录于专栏:Super 前端Super 前端

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

代码语言:javascript
复制
2147483647 === Math.pow(2, 31) - 1 === parseInt('01111111111111111111111111111111', 2)

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

Nodejs 中

代码语言:javascript
复制
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

代码语言:javascript
复制
// 下述 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位,转化为相应毫秒值进行执行!

代码语言:javascript
复制
parseInt('0000000000000000000101110111000', 2) === 3000

上述为 3000 ms

示例1:将第32位变为1

代码语言:javascript
复制
setTimeout(() => {
	console.log(+new Date())
}, parseInt('1000000000000000000101110111000', 2))  // 立即执行

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

代码语言:javascript
复制
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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-03-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Nodejs 中
  • 浏览器
  • 参考地址
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档