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);

優(yōu)網(wǎng)科技秉承"專業(yè)團隊、品質(zhì)服務(wù)" 的經(jīng)營理念,誠信務(wù)實的服務(wù)了近萬家客戶,成為眾多世界500強、集團和上市公司的長期合作伙伴!
優(yōu)網(wǎng)科技成立于2001年,擅長網(wǎng)站建設(shè)、網(wǎng)站與各類業(yè)務(wù)系統(tǒng)深度整合,致力于提供完善的企業(yè)互聯(lián)網(wǎng)解決方案。優(yōu)網(wǎng)科技提供PC端網(wǎng)站建設(shè)(品牌展示型、官方門戶型、營銷商務(wù)型、電子商務(wù)型、信息門戶型、微信小程序定制開發(fā)、移動端應(yīng)用(手機站、APP開發(fā))、微信定制開發(fā)(微信官網(wǎng)、微信商城、企業(yè)微信)等一系列互聯(lián)網(wǎng)應(yīng)用服務(wù)。