Search code examples
javascriptsettimeout

Why does setTimeout() "break" for large millisecond delay values?


I came across some unexpected behavior when passing a large millisecond value to setTimeout(). For instance,

setTimeout(some_callback, Number.MAX_VALUE);

and

setTimeout(some_callback, Infinity);

both cause some_callback to be run almost immediately, as if I'd passed 0 instead of a large number as the delay.

Why does this happen?


Solution

  • This is due to setTimeout using a 32 bit int to store the delay so the max value allowed would be

    2147483647
    

    if you try

    2147483648
    

    you get your problem occurring.

    I can only presume this is causing some form of internal exception in the JS Engine and causing the function to fire immediately rather than not at all.