Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destroy previous setInterval

Tags:

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); } 
like image 707
Eric Fortis Avatar asked Jan 19 '11 00:01

Eric Fortis


People also ask

How do you destroy setInterval in react native?

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); }, []); ...

Do I need to clear setInterval?

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.


2 Answers

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); } 
like image 64
Kyle Wild Avatar answered Oct 28 '22 23:10

Kyle Wild


clearInterval

clearInterval(prevNowPlaying);

you will also want to make the prevNowPlaying from previous calls in scope whereever you try to cancel

like image 37
tobyodavies Avatar answered Oct 29 '22 00:10

tobyodavies