0

I am trying to use setTimeout with a bigint to avoid exceeding the 32 bit integer limit(which did happened in my code) while incrmenting the timeout timer.

setTimeout(console.log, 500n, "I waited 500 ms");

However I got this error thrown: Uncaught TypeError: Cannot convert a BigInt value to a number

I tried to do this:

setTimeout(console.log, Number(500n), "I waited 500 ms");

However I am not sure if the 500 will still be converted to a big integer.

Another thing I tried to do was to convert it using the ++ operator however it threw me the error: Uncaught TypeError: Cannot convert a BigInt value to a number

let _500 = 500n
setTimeout(console.log, _500++, "I waited 500 ms");
The epic face 007
  • 552
  • 1
  • 8
  • 22

3 Answers3

3

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

connexo
  • 53,704
  • 14
  • 91
  • 128
2

This is an XY problem. You are going to get inconsistent results at best setting timeout to max value. Use a cron tool for this.

If this isn't for a server, I'm not sure that any user will keep their browser open for the 24 days (2147483647 millis) that would hit the limit of setTimeout. If this is for a server, a cron tab is really going to serve you better.

If you absolutely must use a large value, you could set up a wrapper that would create new timeouts as the previous one ends until you have waited the entire time.

zero298
  • 25,467
  • 10
  • 75
  • 100
  • What is a "cron tool" – The epic face 007 Mar 18 '21 at 20:28
  • https://www.google.com/search?source=hp&ei=g7hTYOSpFszbgwfq0JmoCA&iflsig=AINFCbYAAAAAYFPGkxoXiEuX8-8DDevNlfkxKqNBBFfv&q=cron+tool&oq=cron+tool&gs_lcp=Cgdnd3Mtd2l6EAMyAggAMgYIABAWEB4yBggAEBYQHjIGCAAQFhAeMgYIABAWEB4yBggAEBYQHjIGCAAQFhAeMgYIABAWEB4yBggAEBYQHjIGCAAQFhAeOg4IABDqAhC0AhDZAhDlAjoICAAQsQMQgwE6BQgAELEDOgUILhCxAzoCCC46CwgAELEDEMcBEKMCOggIABDHARCvAToECAAQCjoICAAQFhAKEB5Q0A5Y0xlg6RtoAXAAeACAAW-IAcwGkgEDNi4zmAEAoAEBqgEHZ3dzLXdperABCA&sclient=gws-wiz&ved=0ahUKEwik98nR17rvAhXM7eAKHWpoBoUQ4dUDCAg&uact=5 – connexo Mar 18 '21 at 20:31
1

2147483647 would be just fine, know your bit limits