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?
Some explanation here: http://closure-library.googlecode.com/svn/docs/closure_goog_timer_timer.js.source.html
This is due to setTimeout using a 32 bit int to store the delay so the max value allowed would be
if you try
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.
You can use:
I stumbled on this when I tried to automatically logout a user with an expired session. My solution was to just reset the timeout after one day, and keep the functionality to use clearTimeout.
Here is a little prototype example:
Usage:
And you may clear it with the
stopTimer
method:is actually not an integer. The maximum allowable value for setTimeout is likely 2^31 or 2^32. Try
and you get 1 back instead of 1.7976931348623157e+308.
Check out the node doc on Timers here: https://nodejs.org/api/timers.html (assuming same across js as well since it's such an ubiquitous term now in event loop based
In short:
When delay is larger than 2147483647 or less than 1, the delay will be set to 1.
and delay is:
The number of milliseconds to wait before calling the callback.
Seems like your timeout value is being defaulted to an unexpected value along these rules, possibly?