停止 JavaScript 中的 setInterval 调用
我正在使用setInterval(fname,10000);
在JavaScript中每10秒调用一次功能。是否可以在某些活动中停止调用它?
我希望用户能够停止重复的数据刷新。
I am using setInterval(fname, 10000);
to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
setInterval()
返回一个间隔ID,您可以将其传递到clearInterval()
:请参阅
setInterval()
andclear Interval()
。setInterval()
returns an interval ID, which you can pass toclearInterval()
:See the docs for
setInterval()
andclearInterval()
.如果将
setInterval
的返回值设置为变量,则可以使用clearInterval
来停止它。If you set the return value of
setInterval
to a variable, you can useclearInterval
to stop it.您可以设置一个新变量,并在每次运行时都会将其递增(计数一个),然后我使用条件语句来结束它:
我希望它有帮助并且是正确的。
You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:
I hope that it helps and it is right.
已经回答了...但是如果您需要一个功能齐全、可重复使用的计时器,并且还支持不同时间间隔的多个任务,您可以使用我的 TaskTimer(适用于 Node 和浏览器)。
在您的情况下,当用户点击干扰数据刷新时;如果需要重新启用,您还可以先调用
timer.pause()
,然后调用timer.resume()
。请参阅更多信息。
Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).
In your case, when users click for disturbing the data-refresh; you can also call
timer.pause()
thentimer.resume()
if they need to re-enable.See more here.
技巧
setInterval
返回一个数字:解决方案
获取此号码。将其传递给函数
clearInterval
即可安全:代码:
始终将
setInterval
返回的数字存储在一个变量,以便您可以稍后停止间隔:(将此数字视为
setInterval
的 ID。即使您调用了多次setInterval
,您仍然可以使用正确的 ID 来停止其中任何一个。)The Trick
setInterval
returns a number:Solution
Take this number. Pass it to the function
clearInterval
and you're safe:Code:
Always store the returned number of
setInterval
in a variable, so that you can stop the interval later on:(Think of this number as the ID of a
setInterval
. Even if you have called manysetInterval
, you can still stop anyone of them by using the proper ID.)在nodeJS中,您可以在setInterval函数中使用“this”特殊关键字。
您可以使用这个 this 关键字来清除间隔,下面是一个示例:
当您在函数中打印 this 特殊关键字的值时,您会输出一个 Timeout 对象
Timeout {...}
In nodeJS you can you use the "this" special keyword within the setInterval function.
You can use this this keyword to clearInterval, and here is an example:
When you print the value of this special keyword within the function you output a Timeout object
Timeout {...}
如果您的计数器位于单击按钮中,请使用此选项。
Use this if you have your counter in a button onclick.
为什么不使用更简单的方法呢?添加班级!
只需添加一个类来告诉间隔不要执行任何操作。例如:悬停时。
多年来我一直在寻找这种快速而简单的方法,因此我发布了多个版本以向尽可能多的人介绍它。
Why not use a simpler approach? Add a class!
Simply add a class that tells the interval not to do anything. For example: on hover.
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.