What is the maximum delay for setInterval?

妖精的绣舞 提交于 2019-11-30 08:00:45

问题


I'm having problems on Firefox 15 and Chrome 21 with the following code:

setInterval(function () { console.log('test') }, 300000000000)

On both browsers, the function is run right away repeats very quickly. Sure, that's a big number (representing about 10 years from now), but I wouldn't expect it to be treated as a tiny or negative number. I haven't seen a maximum allowed delay in any documentation. Does anyone know if there's a standard max, or if this is just the browsers being funny?


回答1:


I can't find any documentation at the moment, but I wouldn't be surprised if the timer value had to fit in a 32-bit signed integer.




回答2:


The interval is stored in a signed 32-bit int (in the tested implementation: V8 in Google Chrome), so the behavior you're seeing is the result of the interval overflowing to a negative number (in which case it behaves as if the interval was 0). Thus, the maximum interval that you can use is 2**31 - 1.

Here's how I determined that this was the case:

setInterval(function(){console.log("hi");}, Math.pow(2,31));

Behaves like the interval is 0.

setInterval(function(){console.log("hi");}, Math.pow(2,31) - 1);

Doesn't fire in the time I was willing to wait.

setInterval(function(){console.log("hi");}, Math.pow(2,33) + 1000);

Behaves like the interval is 1000 (one second). Here, the 2**33 doesn't affect the first 32 bits, so we get just 1000.

The highest possible interval, 2**31-1ms is a little shy of 25 days, so more than enough for anything reasonable.




回答3:


I think that the maximum delay is 231-1 which is 2,147,483,647ms. The maximum value of a signed 32 bit integer in ms. If it would be unsigned it would be 232-1 = 4,294,967,295.




回答4:


Max is 2,147,483,647 (231-1)

Be careful that if you make the number bigger than that, it will run immediately (Imaging that you put a negative value, so the browser will run infinitely loop)

setInterval(()=>console.log('n'),2147483647)
31
setInterval(()=>console.log('y'),2147483648)
38
(1588) y


来源:https://stackoverflow.com/questions/12633405/what-is-the-maximum-delay-for-setinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!