Better timeouts and intervals with Javascript

window.setTimeout and window.setInterval don’t ever seem to have been given any love for a long time. (At least from my limited end-user point of view). I’ve toyed in the past with a better queuing system for them and having the ability to run on clear (especially for intervals), but I’ve actually knocked up a basic script that allows object-oriented timeout events. It still uses the native implementations outside, and I’m sure that this has probably already been done 100 times, but I still wanted to have a go.

This script extends the return from window.setTimeout and window.setInterval to be an object itself that you can stop() and restart(), preserving the function for further use.

var t = window.setTimeout(function(timeout) {
    // timeout argument is the timeout object itself
    console.log('test');
}, 300);
// test
t.restart();
// test
 
var s = window.setInterval(function(interval) {
    // interval argument is the interval object itself
    Messages.check();
}, 1000);
// Interval
s.stop();
// Interval
s.complete;
// 9
s.cancelled;
// 1

Please note: I’ve only really tested this in Chrome! I can’t see why it wouldn’t work in other browsers, I guess maybe some of these would be protected, but I’m not sure… If that’s the case, it wouldn’t be too difficult to utilise the alternative new Timeout(function(){ }, 400); syntax…

There’s a bit more (not much!) of an explanation here and the code is available here. There are no prerequisites for this code, should run on plain old Javascript.

Edit: Minor update to the script to include the object in the callback.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>