如何知道定时器是否在JavaScript中被清除或超时?

问题描述:

好吧,真的很简单的问题。我正在使用JavaScript进行速成课程。如何知道定时器是否在JavaScript中被清除或超时?

如果我使用 timer = setTimeout(..., 500)设置一个计时器,然后clearTimeout(timer)清除计时器,计时器的整数值没有发生变化,所以我的问题是如何知道一个定时器超时或清除?

我想使用if (timer) {...},但显然一个正整数总是返回true。

后,如果您正在寻找一些比较正规的,你可以建立JavaScript类封装了setTimeout/clearTimeout功能。

这样的类可能是这个样子:

/** 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(); 
} 

我还包含一个timerState属性,将让你轻松判断计时器是否“已完成”或“取消”。

你会使用这样的:

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."); 
} 

可以扩展相同的基本想法,如果你需要它包括附加的功能(例如重复计时器,启动/停止/恢复,等等。)

+0

如果jQuery或其他JS框架之一有类似的东西,我不会感到惊讶。任何jQuery专家知道它是否存在? – MatrixFrog 2010-10-26 07:37:46

+0

这真的很全面。谢谢! – lai 2010-10-28 05:04:23

如果清除超时,回调将不会执行。因此,如果执行回调,则意味着自设置超时后已过500ms。

例如:

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

分配null到定时器clearTimeout(timer)

+0

这就是我现在使用的。这似乎是一个事后Javascript在Javascript中。任何更好的方法来处理这个? – lai 2010-10-26 07:07:19

+0

不是我所知道的,对不起:S我认为Win32中的句柄表现相同:) – 2010-10-26 07:26:47

这里是我用于计时器事件的东西!希望这可以帮助。

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; 
     } 
     } 
    } 
    })();