如何知道计时器在javascript中是清除还是超时?

问题描述 投票:7回答:5

好的,非常简单的问题。我在javascript参加速成课程。

如果我使用timer = setTimeout(..., 500)设置定时器,然后使用clearTimeout(timer)来清除定时器,定时器的整数值不会改变,所以我的问题是如何知道定时器是否超时或清除?

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

javascript settimeout
5个回答
12
投票

如果您正在寻找更正式的东西,您可以构建封装setTimeout / clearTimeout功能的javascript类。

这样的类可能看起来像这样:

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

如果需要,您可以扩展相同的基本思想以包含其他功能(例如,重复计时器,开始/停止/恢复等)


4
投票

null之后将clearTimeout(timer)分配给计时器


0
投票

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

例如:

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

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

0
投票

我总是避免在JS中使用标志,但这是一个有意义并保持简单的事情的情况。这个想法是你在计时器触发后设置一个标志,然后你可以在代码的其他地方检查它。

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);
© www.soinside.com 2019 - 2024. All rights reserved.