网站首页 > 知识剖析 正文
大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发。
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
猜你喜欢
- 2025-04-29 typescript - webpack打包警告'mode' option has not been set
- 2025-04-29 通过番计时器实例学习 React 生命周期函数 componentDidMount
- 2025-04-29 Vue3 入门指南: 深入理解 Setup 函数
- 2025-04-29 几句代码写个飞快的下载软件,轻快版 aria2 支持 UPnP,独立 EXE 程序
- 2025-04-29 我终于搞懂了async/await、promise和setTimeout的执行顺序
- 2025-04-29 动手动脑学Kubernetes系列之StatefulSet
- 2025-04-29 setTimeout、Promise、Async/await的区别
- 2025-04-29 [西门子PLC] 博途编程中Set置位和Reset复位指令使用技巧
- 2025-04-29 JSP request.setAttribute()详解及实例
- 2025-04-29 JavaScript 中让 setInterval 立即执行的小技巧
- 04-29php开发者composer使用看这一篇就够了
- 04-29引用和变量声明在不同语言中的实作
- 04-29PHP 没你想的那么差
- 04-29Ubuntu linux 上的 Nginx 和 Php 安装
- 04-29CentOS下通过yum搭建lnmp(单版本PHP)
- 04-29为什么 PHP8 是个高性能版本
- 04-29PHP8函数包含文件-PHP8知识详解
- 04-29使用无参数函数进行命令执行
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)