Reset Timer setInterval ()

var timer; chat.client.addMessage = function (data) { clearTimeout(timer); test2(data); }; timer = setInterval(function () { console.log("working"); test1(); }, 5000); 

I am trying to restart the timer when chat.client.addMessage.SetInterval is ever executed every 5000ms until chat.client.addMessage is executed when this method is executed. setInterval Function stops execution. Help will be appreciated :)

+4
source share
2 answers

You need to use clearInterval instead of clearTimeout , since clearTimeout is the inverse of setTimeout . You can use it in the same way:

 clearInterval(timer); 
+8
source

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 just call him as needed

 chat.client.addMessage = function(data) { resetInterval(); test2(data); }; 
+8
source

Source: https://habr.com/ru/post/1497400/


All Articles