好吧,真的很簡單的問題。我正在使用JavaScript進行速成課程。如何知道定時器是否在JavaScript中被清除或超時?
如果我使用 timer = setTimeout(..., 500)
設置一個計時器,然後clearTimeout(timer)
清除計時器,計時器的整數值沒有發生變化,所以我的問題是如何知道一個定時器超時或清除?
我想使用if (timer) {...}
,但顯然一個正整數總是返回true。
好吧,真的很簡單的問題。我正在使用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.");
}
可以擴展相同的基本想法,如果你需要它包括附加的功能(例如重複計時器,啓動/停止/恢復,等等。)
如果清除超時,回調將不會執行。因此,如果執行回調,則意味着自設置超時後已過500ms。
例如:
var timer = setTimeout(function() {
alert('you will never see this alert');
}, 500);
clearTimeout(timer);
分配null
到定時器clearTimeout(timer)
這就是我現在使用的。這似乎是一個事後Javascript在Javascript中。任何更好的方法來處理這個? – lai 2010-10-26 07:07:19
不是我所知道的,對不起: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;
}
}
}
})();
如果jQuery或其他JS框架之一有類似的東西,我不會感到驚訝。任何jQuery專家知道它是否存在? – MatrixFrog 2010-10-26 07:37:46
這真的很全面。謝謝! – lai 2010-10-28 05:04:23