Overriding setInterval with a better implementation

JavaScript includes two built-in options for timing and delaying actions, setInterval() and setTimeout(). These functions have been around since before the first ECMA specifications, so their implementations across browsers are largely non-standardized and inconsistent. I’ve noticed some problems with setInterval(), particularly when it’s left in a background tab.

[Skip all this and go straight to the code on GitHub]

The problem

Some browsers will delay or ignore setInterval() actions when a tab is in the background, and then rush to catch up with the backlog of actions when the tab is switched back to the foreground. This can cause the browser to freeze for a noticeable length of time while the intervals catch up. Luckily setTimeout() doesn’t seem to suffer from the same drawbacks, so I wrote this override function to replace the default implementation of setInterval() with one that relies entirely on setTimeout().

I decided to override the existing setInterval() function instead of creating a new function that behaved similarly so that this code could be dropped into any existing system as-is. Said system should continue to behave exactly the same way (without the performance bugs of course).

Accounting for clearInterval()

I built this override to function in exactly the same way as setInterval(), meaning I had to create the functionality of clearInterval() as well. I accomplished this by treating the new setInterval() function as an object, and keeping track of each created interval as a property on that object.

Each property on the setInterval object contains the function passed when the interval was created as well as an additional property signifying whether or not the interval is still active. When an interval is cleared that property is changed so the interval will no longer execute.

Handling all cases of setInterval() arguments

setInterval() and setTimeout() can be called with several different sets of arguments. The second argument is always a number specifying the number of milliseconds to wait between each interval, and the first can either be a function handler or a string. If it’s a string, eval() will be called on the string to execute it. If it’s a function handler, it can either be executed immediately or executed with a series of arguments passed as the 3rd, 4th, 5th, etc. arguments of the timing function.

Return value and using clearInterval()

The custom setInterval() function returns an object that can be used to target the newly created interval and cancel it.

This object is then used by the custom clearInterval() function to set the active state of that interval to false.

Tagged with: ,
Posted in Custom Library Functions, GitHub, JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *