如何将 setTimeout 与 bigint 一起使用?
How can I use setTimeout with bigint?
我正在尝试将 setTimeout 与 bigint 一起使用,以避免在增加超时计时器时超过 32 位整数限制(这确实发生在我的代码中)。
setTimeout(console.log, 500n, "I waited 500 ms");
但是我抛出了这个错误:
Uncaught TypeError: Cannot convert a BigInt value to a number
我试过这样做:
setTimeout(console.log, Number(500n), "I waited 500 ms");
不过我不确定 500 是否仍会转换为大整数。
我尝试做的另一件事是使用 ++
运算符转换它,但是它给我带来了错误:
Uncaught TypeError: Cannot convert a BigInt value to a number
let _500 = 500n
setTimeout(console.log, _500++, "I waited 500 ms");
2147483647 就好了,知道你的位限制
这是一个 XY problem. You are going to get inconsistent results at best setting timeout to max value. Use a cron 工具。
如果这不是针对服务器,我不确定任何用户都会将浏览器打开 24 天(2147483647 毫秒),这会达到 setTimeout
的限制。如果这是用于服务器,那么 cron 选项卡确实会更好地为您服务。
如果你绝对必须使用一个大的值,你可以设置一个包装器,它会在前一个超时结束时创建新的超时,直到你等待整个时间。
Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately.
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#maximum_delay_value
我正在尝试将 setTimeout 与 bigint 一起使用,以避免在增加超时计时器时超过 32 位整数限制(这确实发生在我的代码中)。
setTimeout(console.log, 500n, "I waited 500 ms");
但是我抛出了这个错误:
Uncaught TypeError: Cannot convert a BigInt value to a number
我试过这样做:
setTimeout(console.log, Number(500n), "I waited 500 ms");
不过我不确定 500 是否仍会转换为大整数。
我尝试做的另一件事是使用 ++
运算符转换它,但是它给我带来了错误:
Uncaught TypeError: Cannot convert a BigInt value to a number
let _500 = 500n
setTimeout(console.log, _500++, "I waited 500 ms");
2147483647 就好了,知道你的位限制
这是一个 XY problem. You are going to get inconsistent results at best setting timeout to max value. Use a cron 工具。
如果这不是针对服务器,我不确定任何用户都会将浏览器打开 24 天(2147483647 毫秒),这会达到 setTimeout
的限制。如果这是用于服务器,那么 cron 选项卡确实会更好地为您服务。
如果你绝对必须使用一个大的值,你可以设置一个包装器,它会在前一个超时结束时创建新的超时,直到你等待整个时间。
Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately.
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#maximum_delay_value