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

发布于 2024-09-29 05:56:52 字数 241 浏览 9 评论 0原文

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

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

白昼 2024-10-06 05:56:52

如果您正在寻找更正式的东西,您可以构建封装 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.");
}

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

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.)

偏爱你一生 2024-10-06 05:56:52

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

assign null to the timer after the clearTimeout(timer)

じ违心 2024-10-06 05:56:52

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

例如:

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

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);
农村范ル 2024-10-06 05:56:52

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

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

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;
        }
      }
    }
  })();
淡淡の花香 2024-10-06 05:56:52

我一般会避免在 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);

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文