检查clearInterval是否被调用?
给出这段代码:
bob = setInterval(function, 1000);
clearInterval(bob);
现在有办法知道该间隔是否已被清除吗?
目前,我自己通过取消设置“bob
”来跟踪这一点,但我很好奇我的额外代码行是否是不必要的:
clearInterval(bob);
bob = null;
if (!bob) itIsCleared();
谢谢!
Given this code:
bob = setInterval(function, 1000);
clearInterval(bob);
Is there now a way to know if that interval has been cleared?
Currently, I keep track of this myself, by unsetting 'bob
', but I'm curious if my extra line of code is unnecessary:
clearInterval(bob);
bob = null;
if (!bob) itIsCleared();
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
setInterval
的返回值只是一个唯一 ID,您可以用来传回clearInterval
。它不是具有任何附加信息的结构化对象,当您调用clearTimeout
时,它也不会设置为 null。The return value of
setInterval
is just a unique id you use to pass back toclearInterval
. It's not a structured object with any additional information, nor does it get set to null when you callclearTimeout
.所以这是一个很晚的答案,但如果你这样做,
它会强制变量
myInterval
未定义,因此你可以通过执行if(!this.我的间隔)
So this is a very late answer but if you do something like this
It will force the variable
myInterval
to be undefined and thus you can check the clearing of the interval by doingif(!this.myInterval)
bob 仅包含用于清除它的间隔的 id。当您调用clearInterval时,它会获取与该id关联的间隔并将其清除。 id 根本没有改变。
请参阅此处进行演示
示例:
这将显示间隔的 id(之前由 setInterval 返回)。如果你知道间隔的id是1,你可以使用clearInterval(1)来清除间隔。因此,使用将 bob 设置为 null 的方法是一个很好的方法。只要确保如果 bob 恰好为 0,!bob 不会返回 true。:D
bob only contains an id of the interval used to clear it. When you call clearInterval, it gets the interval associated with that id and clears it. The id isn't changed at all.
see here for demonstration
example:
This will show you the interval's id (returned by setInterval earlier). If you know the interval's id is 1, you can just use clearInterval(1) to clear the interval. So your way of using setting bob to null is a good way of doing it. Just be sure that !bob doesn't return true if the bob happens to be 0. :D