领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

setTimeout 出大 bug?为什么需要 setBigTimeout?

nixiaole 2025-04-29 03:05:08 知识剖析 2 ℃

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发。

1.setTimeout 的隐含 "bug"

setTimeout 是 JavaScript 中一种延迟代码的方式,其需要开发者提供一个以毫秒为单位的超时时间,以及一个在该时间结束后调用的函数。

setTimeout(() => {
  console.log("This runs after 2 seconds");
}, 2000);

在大多数 JavaScript 运行时中,时间数据表示为 32 位有符号整数。这意味着最大超时时间约为 2,147,483,647 毫秒,或约 24.8 天。对于大多数开发者来说已经足够,但在特殊情况下尝试设置更大的超时时间则会发生奇怪的事情。

例如,下面代码导致立即执行 setTimeout,因为 2**32 - 5000 溢出为负数:

// -4294967296 + 2^32,即 -4294967296 + 4294967296 = 0
setTimeout(() => console.log("hi!"), 2 ** 32 - 5000);

而以下代码会导致大约 5 秒后执行 setTimeout 回调:

setTimeout(() => console.log("hi!"), 2 ** 32 + 5000);

最后值得注意的是,以上行为与 Node.js 中的 setTimeout 并不匹配,在 Node.js 中,任何大于 2,147,483,647 毫秒的 setTimeout 都会导致立即执行。

2. 使用超时时间链接的方式实现更大时间的定时器 setTimeout

针对以上情况,开发者其实可以通过将多个较短的 timeout 链接在一起来实现更长时间的超时设置,且每一个超时时间都不超过 setTimeout 的限制。

首先编写一个新的超时函数,即 setBigTimeout:

const MAX_REAL_DELAY = 2 ** 30;
const clear = Symbol("clear");
class BigTimeout {
  #realTimeout = null;
  constructor(fn, delay) {
    if (delay < 0) {
      throw new Error("延迟时间不能是负数");
    }
    let remainingDelay = delay;
    // 延迟计算要考虑是 bigint 还是 number 类型
    const subtractNextDelay = () => {
      if (typeof remainingDelay === "number") {
        remainingDelay -= MAX_REAL_DELAY;
      } else {
        remainingDelay -= BigInt(MAX_REAL_DELAY);
      }
    };
    // 调用计数函数
    const step = () => {
      if (remainingDelay> MAX_REAL_DELAY) {
        subtractNextDelay();
        // 继续执行 step 方法实现更长时间的延迟
        this.#realTimeout = setTimeout(step, MAX_REAL_DELAY);
      } else {
        // 直接执行 fn 回调方法
        this.#realTimeout = setTimeout(fn, Number(remainingDelay));
      }
    };
    step();
  }
  [clear]() {
    if (this.#realTimeout) {
      clearTimeout(this.#realTimeout);
      this.#realTimeout = null;
    }
  }
}
// setBigTimeout 的 API 使用方式与 setTimeout 基本一致
export const setBigTimeout = (fn, delay) => new BigTimeout(fn, delay);
export const clearBigTimeout = (timeout) => {
  if (timeout instanceof BigTimeout) {
    timeout[clear]();
  } else {
    clearTimeout(timeout);
  }
};

MAX_REAL_DELAY 值的设置需要满足以下条件:

  • 小于 Number.MAX_SAFE_INTEGER
  • 小于 setTimeout 的最大值

同时,将该值设置得较大非常有用,因为可以最大限度地减少占用主线程的时间,虽然并非什么大问题。最后值得一提的是,setBigTimeout 允许任意的延迟时间,即同时支持 number 或 bigint 数据类型。

当然,清除定时器也非常简单,可以直接调用 clearBigTimeout 方法:

import {clearBigTimeout, setBigTimeout} from "./clearTimeout.js";
const timeout = setBigTimeout(() => {
  console.log("This will never be executed");
}, 123456789);
// 首先设置定时器然后清除
clearBigTimeout(timeout);

参考资料

https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout

https://dev.to/mrrishimeena/settimeout-is-not-the-same-as-you-think-44ep

最近发表
标签列表