This is a
legacy page.

Interval & Timeout Classes for JavaScript

Warning: See the note about compatibility below.

In most newer browsers, the native window.setInterval and window.setTimeout functions can be used in either of these two ways:

window.setInterval(code, interval);
window.setTimeout(code, delay);
// or...
window.setInterval(function, interval, args...);
window.setTimeout(function, delay, args...);

I much prefer to pass a function, because that way the function and arguments don't have to be global. However, some older browsers, including Internet Explorer 5 for Macintosh, only support passing a string of JavaScript code.

To solve this, here are two classes, Interval and Timeout, both of which operate exclusively on the functions-and-arguments approach.

Implementation Details

The Interval class detects whether the browser's window.setInterval implementation can accept functions. If it determines that the browser is capable, then it just uses that native functionality. If not, it implements the functionality itself. The Timeout class works by using Interval.

Usage

This is all transparent, so you don't need to do any browser detection yourself. The only thing about using it that's different from setInterval and setTimeout is that instead of calling functions to set and clear them, you create a new instance, and call its clear method:

// to set them up...
var i = new Interval(function, interval, args...);
var t = new Timeout(function, delay, args...);

// to clear them...
i.clear();
t.clear();

Files

Compatibility

I've had two reports of the tests below failing: one in Safari/417.8 PPC, and one in Opera/9.21 for Windows. The tests have passed in every other browser, including older versions of Safari and Opera, MSIE 6+, and Firefox 1.5+.

Therefore, more troubleshooting is needed to determine what is at fault: my Interval class, my tests, or the browsers' built-in setInterval function.

I won't have time to troubleshoot any time soon, but you're invited to help do that. You can also help by running the test and submitting your results, especially if you have either of the browsers that have failed the tests in the past.

Advertisements