--- title: WindowOrWorkerGlobalScope.clearTimeout() slug: Web/API/clearTimeout tags: - API - WindowOrWorkerGlobalScope - clearTimeout translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout original_slug: Web/API/WindowOrWorkerGlobalScope/clearTimeout ---
{{domxref("WindowOrWorkerGlobalScope")}}内置的clearTimeout()
方法取消了先前通过调用{{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}建立的定时器。
scope.clearTimeout(timeoutID)
timeoutID
setTimeout()
调用返回。值得注意的是,{{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}和{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}使用共享的ID池, 意味着在技术上可以混用clearTimeout()
和{{domxref("WindowOrWorkerGlobalScope.clearInterval", "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 |
---|---|---|
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'WindowOrWorkerGlobalScope.clearTimeout()')}} | {{Spec2("HTML WHATWG")}} | Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec. |
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'clearTimeout()')}} | {{Spec2('HTML WHATWG')}} |
{{CompatibilityTable}}
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 1.0 | {{CompatVersionUnknown}} | {{CompatGeckoDesktop("1")}} {{CompatGeckoDesktop("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 | {{CompatVersionUnknown}} | {{CompatGeckoMobile("1")}} {{CompatGeckoMobile("52")}}[1] |
6.0 | 6.0 | 1.0 |
[1] clearTimeout()
now defined on {{domxref("WindowOrWorkerGlobalScope")}} mixin.