检查是否已清除超时?

cho*_*bo2 36 javascript

我想知道有没有办法判断是否仍然设置超时

var t=setTimeout("alertMsg()",3000);
Run Code Online (Sandbox Code Playgroud)

当你清除它时我觉得它会像未定义的那样.但它似乎有一些不被清除的id.

Rei*_*eid 44

不是直接的,但您可以创建一个包装器对象来提供该功能.粗略的实现是这样的:

function Timeout(fn, interval) {
    var id = setTimeout(fn, interval);
    this.cleared = false;
    this.clear = function () {
        this.cleared = true;
        clearTimeout(id);
    };
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

var t = new Timeout(function () {
    alert('this is a test');
}, 5000);
console.log(t.cleared); // false
t.clear();
console.log(t.cleared); // true
Run Code Online (Sandbox Code Playgroud)

我的第一个想法是替换__CODE____CODE__修改其参数的新函数(将它们的旧值存储在闭包中),但后来我意识到__CODE__返回一个数字,这是一个原语(因此通过值传递).我想如果我要开始返回非基元,我不妨只做一个包装器对象,这将允许更多的灵活性.但是,这种方法可能就像你想要的那样 - 如果是这样,我可以提供适当的代码,如果你需要一个例子.

希望这可以帮助.


jor*_*aul 20

首先,我对Reid的部分回答表示赞赏,但我觉得我应该补充一些建议.随着我对Reid代码的轻微补充,这将:

  • 超时自然到期时自动清除
  • 可选地设置超时功能的范围(而不是仅在全局范围内执行).
  • 可选地将arguments数组传递给timeout函数

这里是:

function Timeout(fn, interval, scope, args) {
    scope = scope || window;
    var self = this;
    var wrap = function(){
        self.clear();
        fn.apply(scope, args || arguments);
    }
    this.id = setTimeout(wrap, interval);
}
Timeout.prototype.id = null
Timeout.prototype.cleared = false;
Timeout.prototype.clear = function () {
    clearTimeout(this.id);
    this.cleared = true;
    this.id = null;
};
Run Code Online (Sandbox Code Playgroud)

[开始评论免费插件] 哦,我正在使用添加方法的原型模型到类,但只是因为我更喜欢它,不是因为我觉得它更正确 [end comment-free plug]


Gav*_*vin 9

在你的超时函数中设置t0(或在你的情况下为t):

timeoutID = 0;
Run Code Online (Sandbox Code Playgroud)

如果使用clearTimeout它,则将超时ID设置为0,因此检查是否timeoutID === 0将被清除或完成.


use*_*716 5

不。为了知道,您需要t在调用后将变量清空clearTimeout。否则,确实没有任何指标。

仅供参考,最好将直接引用传递给函数,而不要传递将要求值的字符串。

var t=setTimeout(alertMsg,3000);
Run Code Online (Sandbox Code Playgroud)