setTimeout() - an edge case

setTimeout() - an edge case

Divyajyoti Ukirde's photo
Divyajyoti Ukirde
·Sep 5, 2020·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

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!

Other Blogposts you might like to checkout!

Share this