2010-10-26 2842 views
7

好吧,真的很簡單的問題。我正在使用JavaScript進行速成課程。如何知道定時器是否在JavaScript中被清除或超時?

如果我使用 timer = setTimeout(..., 500)設置一個計時器,然後clearTimeout(timer)清除計時器,計時器的整數值沒有發生變化,所以我的問題是如何知道一個定時器超時或清除?

我想使用if (timer) {...},但顯然一個正整數總是返回true。

回答

12

後,如果您正在尋找一些比較正規的,你可以建立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

0

如果清除超時,回調將不會執行。因此,如果執行回調,則意味着自設置超時後已過500ms。

例如:

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

分配null到定時器clearTimeout(timer)

+0

這就是我現在使用的。這似乎是一個事後Javascript在Javascript中。任何更好的方法來處理這個? – lai 2010-10-26 07:07:19

+0

不是我所知道的,對不起:S我認爲Win32中的句柄表現相同:) – 2010-10-26 07:26:47

0

這裏是我用於計時器事件的東西!希望這可以幫助。

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; 
     } 
     } 
    } 
    })(); 
相關問題