DEV Community

Cover image for setTimeout() - any drawback?
Divyajyoti Ukirde
Divyajyoti Ukirde

Posted on • Updated on

setTimeout() - any drawback?

Recently, I had come across a bug that needed auto-refresh after a certain point of time. And setTimeout() had been used to count down to the time and reload the page. Little did I know that setTimeout() came with a price.

As quoted on MDN Web Docs at the very bottom, "Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately."

Now, you'll understand what kept happening to the page! (The page kept reloading...)

It is very much true that there is hardly any process that would require this big a delay. You have other options, like reseting timer after certain duration or using setInterval().

I would prefer setInterval(), when there are simple operations in the callback function and when you know what is the maximum time that function is going to take to execute. If you aren't aware of the maximum time, the event queue will keep piling up forever as your code's activity lags behind the actual system time.

Choose wise! Don't forget to clear the timers when your job is done!

Top comments (4)

Collapse
 
mxldevs profile image
MxL Devs

A competition to see whose computer can stay on the longest without getting kicked off by windows update.

Collapse
 
kahn profile image
Karim Hussain

They do that to test browsers for memory leaks. Google and Microsoft for example has a computer with Chrome / Edge open and running that they manually check every morning to make sure it's performant and running.

Collapse
 
mxldevs profile image
MxL Devs

Interesting. I'm broadly aware of issues that can arise due to limitations of underlying data types (eg 32 bit ints or even 16 or 8 bit ints or less for those that really try to optimize space).

Interval sounds like it definitely would be more suitable if factors like "total time elapsed since the beginning" is not necessary.

Collapse
 
_ajay_gupta profile image
Ajay Gupta • Edited

I am wondering, Browser will work more than 24 days. is anybody would have been tested this scenario.