I want a function to set an Ajax and a reload timer. The code below doesn't destroy the previous function call timer, so each time I invoke it I get another timer. How can I destroy the previous timer?
function initNowPlayingMeta(station) { $('#cancion').children().remove(); $('#cancion').load('sonando.php?emisora=' + station); var prevNowPlaying = setInterval(function () { $('#cancion').load('sonando.php?emisora=' + station); }, 5000); }
Clearing setInterval in React To stop an interval, you can use the clearInterval() method. ... useEffect(() => { const interval = setInterval(() => { setSeconds(seconds => seconds + 1); }, 1000); return () => clearInterval(interval); }, []); ...
SetInterval() does not change the speed that you pass it. If whatever it is doing speeds up each time that you call SetInterval(), then you have multiple timers which are running at the same time, and should open a new question. Make sure you are really stopping it.
You need to store your timer reference somewhere outside of local scope (this essentially means declaring it with var
outside of the function). Then, clear it with clearInterval
:
var prevNowPlaying = null; function initNowPlayingMeta(station) { if(prevNowPlaying) { clearInterval(prevNowPlaying); } $('#cancion').children().remove(); $('#cancion').load('sonando.php?emisora=' + station); prevNowPlaying = setInterval(function () { $('#cancion').load('sonando.php?emisora=' + station); }, 5000); }
clearInterval
clearInterval(prevNowPlaying);
you will also want to make the prevNowPlaying from previous calls in scope whereever you try to cancel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With