javascript 重置 setInterval() 的计时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18270009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reset Timer of setInterval()
提问by user2137186
var timer;
chat.client.addMessage = function (data) {
clearTimeout(timer);
test2(data);
};
timer = setInterval(function () {
console.log("working");
test1();
}, 5000);
I am trying to restart timer when ever chat.client.addMessage is executed.SetInterval is executed after every 5000ms until chat.client.addMessage is executed when ever that method is executed setInterval Function stops executing . Help will be appreciated:)
我试图在执行 chat.client.addMessage 时重新启动计时器。每 5000 毫秒后执行一次 SetInterval,直到执行该方法时执行 chat.client.addMessage setInterval 函数停止执行。帮助将不胜感激:)
回答by CodingIntrigue
You need to use clearIntervalinstead of clearTimeout
as clearTimeout is the inverse of setTimeout. You can use it in the same manner:
您需要使用clearInterval而不是clearTimeout
clearTimeout 是setTimeout的倒数。您可以以相同的方式使用它:
clearInterval(timer);
回答by Jae
you need to add a function that clears the interval and then restarts it
您需要添加一个清除间隔然后重新启动它的函数
function resetInterval() {
clearInterval(timer);
timer = setInterval(function() {
console.log("restarted interval");
test1();
}, 5000);
}
then you can simply call it as needed
然后你可以根据需要简单地调用它
chat.client.addMessage = function(data) {
resetInterval();
test2(data);
};