chobo2 chobo2 - 1 year ago 97
Javascript Question

Check if a timeout has been cleared?

I am wondering is there a way to tell if a timeout is still set

var t=setTimeout("alertMsg()",3000);

I thought t would be like undefined when you clear it. But it seems to have some id that does not get cleared.

Answer Source

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;

Then you can do something like:

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

My first idea was to replace setTimeout and clearTimeout with new functions (storing their old value in a closure) that modified their arguments, but then I realized that setTimeout returns a number, which is a primitive (and thus passed by value). I figured that if I was going to start returning non-primitives, I might as well just make a wrapper object, which would allow more flexibility. However, that method may be something like what you want too -- if so, I can provide the appropriate code if you need an example to go by.

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download