Search code examples
javascriptsettimeout

How can I use setTimeout with bigint?


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

Solution

  • 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.