检查是否已清除超时? [英] Check if a timeout has been cleared?

查看:117
本文介绍了检查是否已清除超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wondering is there a way to tell if a timeout is still set

var t=setTimeout("alertMsg()",3000);

当你清除它时,我认为是未定义的。但它似乎有一些不会被清除的id。

I thought t would be like undefined when you clear it. But it seems to have some id that does not get cleared.

推荐答案

不是直接的,但你可以创建一个包装器对象来给出那个功能。粗略的实现是这样的:

Not directly, but you can create a wrapper object to give that functionality. A rough implementation is like so:

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

然后你可以这样做:

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

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

My first idea was to replace setTimeout and clearTimeout with new functions (storing their old value in a closure) that modified their arguments, but then I realized that setTimeout returns a number, which is a primitive (and thus passed by value). I figured that if I was going to start returning non-primitives, I might as well just make a wrapper object, which would allow more flexibility. However, that method may be something like what you want too -- if so, I can provide the appropriate code if you need an example to go by.

希望这有助于。

这篇关于检查是否已清除超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆