Check if a timeout has been cleared?

First of all, I am giving credit to Reid for portions of this answer, however I felt that I should add some suggestions. With my slight additions to Reid's code, this will:

  • auto-clear when the timeout naturally expires
  • optionally set the scope of the timeout function (rather than just executing in global scope).
  • optionally pass arguments array to the timeout function

here it is:

function Timeout(fn, interval, scope, args) {
    scope = scope || window;
    var self = this;
    var wrap = function(){
        self.clear();
        fn.apply(scope, args || arguments);
    }
    this.id = setTimeout(wrap, interval);
}
Timeout.prototype.id = null
Timeout.prototype.cleared = false;
Timeout.prototype.clear = function () {
    clearTimeout(this.id);
    this.cleared = true;
    this.id = null;
};

[begin comment-free plug] Oh, and I am using the prototype model of adding methods to classes, but only because I prefer it, not because I feel it is more correct [end comment-free plug]


Not directly, but you can create a wrapper object to give that functionality. A rough implementation is like so:

function Timeout(fn, interval) {
    var id = setTimeout(fn, interval);
    this.cleared = false;
    this.clear = function () {
        this.cleared = true;
        clearTimeout(id);
    };
}

Then you can do something like:

var t = new Timeout(function () {
    alert('this is a test');
}, 5000);
console.log(t.cleared); // false
t.clear();
console.log(t.cleared); // true

Tags:

Javascript