HTML清除计时器的语句,如何知道计时器是否被清除或在javascript中超时?

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

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值