Better timeouts and intervals with Javascript

Not really much to show, but feel free to try experimenting in your console!

The main reasons for wanting to have this ability are so you could do things like:

var t = window.setInterval(function(interval) {

    if (!User.signedIn()) {
}, 30000);

// some time later...

// will execute User.update(); before clearing the interval

if you change the script setting the 'expose' paramter to true, you can use these custom constructors:

var t = new Interval(function(interval) {

    if (!User.signedIn()) {
}, 30000);
// which would be exactly the same

The public properties of the returned objects are:

    active: true        // whether or not the object is active
    complete: 3,        // the number of times the object has been run
    cancelled: 0,       // the number of times the object has been manually stopped
    delay: 30000,       // the delay it was set up with, changing this, then calling restart will use the new delay
    fn: function,       // the function it will run, this will be passed the timeout/interval as the first argument
    id: 0,              // the internal id in the queue
    interval/timeout: 1 // the true native id of the object, the key differs depending on if it's a timeout or an interval

and the instance methods are:

For fun and profit all methods return the object, so you could set up t and run:


if you really, REALLY, wanted.

Back to blog post

Download the script (.tar.gz)

Minor updates: 17th April 2012. Passing the timeout/interval object to the callback.