Home > Net >  SetInterval fires constantly (0ms) for seemingly arbitrary large numbers
SetInterval fires constantly (0ms) for seemingly arbitrary large numbers

Time:07-30

This is not practical, but I am absolutely baffled.

The only code I'm using is this following 2 lines over and over again with different numbers in a browser console:

var i = setInterval(() => console.log('test'), INTERVAL_VALUE);
clearInterval(i);

I was trying to test a number input which controlled a setInterval timer when I accidentally found that if I just typed a huge random number into the box (as any good QA tester would), it started bugging out. I thought it was an issue with my own code but I've reduced it down to the above pitifully minimal reproducible case. For some reason, certain ranges of large numbers for the interval cause it to behave as if the value 0 was given (ie. it prints "test" to the console hundreds of times per second).

One such example range is [11,000,000,000 - 12,000,000,000]. The range isn't exact, as it extends a bit beyond the bounds in both directions and I haven't found the exact bounds, but all values within that range cause problems (including the value I discovered this with: 12,345,678,900). If you do 10,000,000,000 or 13,000,000,000 though then it (seemingly) works as expected (at least, it didn't rapid fire, it's hard to test a 5 month interval).

Trying random numbers, I was able to find much larger numbers (20 digits) that both do and don't trigger this problem, it seems to be arbitrary, or at least not related to scale.

Is this a known problem? Does anyone have any idea why it might be happening? I have to imagine its some sort of float rounding error or something like that. It's obviously not a problem for most developers that you can't set a 5 month timer in the browser but it's weird nonetheless and not documented AFAIK.

CodePudding user response:

From MDN:

Note: The delay argument is converted to a signed 32-bit integer. This effectively limits delay to 2147483647 ms, since it's specified as a signed integer in the IDL.

You're picking a number larger than can fit in a 32 bit number, so when it gets converted it will sometimes wrap around to a negative number (if it's in the right range).

  • Related