WindowOrWorkerGlobalScope内置的clearTimeout()方法取消了先前通过调用setTimeout()建立的定时器。

语法

scope.clearTimeout(timeoutID)

 

Parameters

timeoutID
您要取消定时器的标识符。 该ID由相应的setTimeout()调用返回。

值得注意的是,setTimeout()setInterval()使用共享的ID池, 这意味着你可以在技术上交替使用clearTimeout()clearInterval() 。 但是,为了清楚起见,你应该避免这样做。

示例

在一个网页中运行如下脚本,并且点击一次页面。一秒钟后你会看见弹出一条信息。如果你在一秒内不停点击页面,弹出框将不再出现。

var alarm = {
  remind: function(aMessage) {
    alert(aMessage);
    delete this.timeoutID;
  },

  setup: function() {
    this.cancel();
    var self = this;
    this.timeoutID = window.setTimeout(function(msg) {self.remind(msg);}, 1000, "Wake up!");
  },

  cancel: function() {
    if(typeof this.timeoutID == "number") {
      window.clearTimeout(this.timeoutID);
      delete this.timeoutID;
    }
  }
};
window.onclick = function() { alarm.setup() };

注意

传入一个错误的 ID 给 clearTimeout()不会有任何影响;也不会抛出异常。

规范

Specification Status Comment
HTML Living Standard
WindowOrWorkerGlobalScope.clearTimeout()
Living Standard Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
HTML Living Standard
clearTimeout()
Living Standard  

浏览器兼容

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support 1.0 (Yes) 1.0 (1.7 or earlier)
52 (52)[1]
4.0 4.0 1.0
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 1.0 1.0 (Yes) 1.0 (1)
52.0 (52)[1]
6.0 6.0 1.0

[1] clearTimeout() now defined on WindowOrWorkerGlobalScope mixin.

更多

文档标签和贡献者

此页面的贡献者: zhangchen, luojia, paddingme
最后编辑者: zhangchen,