9

Ok, really simple question. I'm taking a crash course in javascript.

If I use timer = setTimeout(..., 500) to set a timer, and then clearTimeout(timer) to clear the timer, the integer value of timer doesn't change, so my question is how to know if a timer is timed out or cleared?

I want to use if (timer) {...} , but obviously a positive integer always returns true.

5 Answers 5

13

If you're looking for something more formal, you could build javascript class that encapsulates the setTimeout/clearTimeout functionality.

Such a class might look something like this:

/** class Timer **/
var Timer = function(delayMs, callbackFunc) {
    this.delayMs = delayMs;
    this.callbackFunc = callbackFunc;
    this.timerState = 'new';
}
Timer.prototype.start = function() {
    if( this.tmr ) return;

    var self = this;
    this.timerState = 'running';
    this.tmr = setTimeout(function() { self._handleTmr(); }, this.delayMs);
}
Timer.prototype.cancel = function() {
    if( ! this.tmr ) return;

    clearTimeout(this.tmr);
    this.tmr = null;
    this.timerState = 'canceled';
}
Timer.prototype._handleTmr = function() {
    this.tmr = null;
    this.timerState = 'completed';
    this.callbackFunc();
}

I've also included a timerState attribute that would let you easily determine whether the timer was "completed" or "canceled".

You would use it like this:

var t = new Timer(500, function() {
    alert('timer completed');
});
t.start();

// do whatever...

// now cancel the timer if it hasn't completed yet.
t.cancel();

// maybe you do some other stuff...
// then check the timerState, and act accordingly.
//
if( t.timerState == 'canceled' ) {
   alert("the timer was canceled!");
} else {
   alert("the timer completed uneventfully.");
}

You can extend the same basic idea to include additional functionality if you need it (eg. repeating timer, start/stop/resume, etc.)

2
  • I would not be surprised at all if jQuery or one of the other JS frameworks had something like this. Any jQuery experts know if it exists or not?
    – Tyler
    Oct 26, 2010 at 7:37
  • This is really comprehensive. Thanks!
    – lai
    Oct 28, 2010 at 5:04
5

assign null to the timer after the clearTimeout(timer)

2
  • This is what I'm using now. It seems like a afterthought in Javascript. Any better ways to handle this?
    – lai
    Oct 26, 2010 at 7:07
  • not that I know of, sorry :S I think handles in Win32 behaved the same :) Oct 26, 2010 at 7:26
0

If you clear the timeout the callback won't be executed. So if the callback is executed it means that 500ms have passed since you've set the timeout.

For example:

var timer = setTimeout(function() {
    alert('you will never see this alert');
}, 500);
clearTimeout(timer);
0

Here is something that I use for timer events! Hope this helps.

    var toggleTimeOut   = (function () {

    var _timeout;

    return function (clear_timeout) {

      if(!clear_timeout) 
      {
        _timeout    =   setTimeout( function () {/*DO YOUR STUFF*/}, 5000);
      }
      else
      {
        if(typeof _timeout != typeof undefined && _timeout != 0)
        {
            clearTimeout(_timeout);
            _timeout= 0;
        }
      }
    }
  })();
0

I avoid using flags in JS in general but this is a case where it makes sense and keeps things nice and simple. The idea is you set a flag once your timer has fired and then you can examine that elsewhere in code.

let fired = false;

// Set your timeout to do future work...
const timeout = window.setTimeout(() => {
    fired = true;
    // ...
}, 3000);

// Test it
const testInterval = window.setInterval(() => {
    console.log(`Timer has ${fired ? ' ' : 'not '}fired`);
    fired && window.clearInterval(testInterval);
}, 500);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.