views:

101

answers:

2

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?

+2  A: 

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.

HTH

OneSHOT

OneSHOT
Okay, that makes sense. I'm guessing it doesn't actually raise an internal exception. Instead, I see it either (1) causing an integer overflow, or (2) internally coercing the delay to an unsigned 32-bit int value. If (1) is the case, then I'm really passing a negative value for the delay. If it's (2), then something like [`delay >>> 0`](http://stackoverflow.com/questions/3081987/) happens, so the delay passed is zero. Either way, the fact that the delay is stored as a 32-bit unsigned int explains this behavior. Thanks!
Matt Ball
+1  A: 
Number.MAX_VALUE

is actually not an integer. The maximum allowable value for setTimeout is likely 2^31 or 2^32. Try

parseInt(Number.MAX_VALUE) 

and you get 1 back instead of 1.7976931348623157e+308.

Osmund