开发者

Destroy previous setInterval

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.p开发者_如何学JAVAhp?emisora=' + station);
    var prevNowPlaying = setInterval(function () {
        $('#cancion').load('sonando.php?emisora=' + station);
    }, 5000);
}


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


You need to explicitly clear the timer.

var prevNowPlaying;
function initNowPlayingMeta(station) {
    $('#cancion').children().remove();
    $('#cancion').load('sonando.php?emisora=' + station);
    if (prevNowPlaying === undefined) clearInterval(prevNowPlaying);
    prevNowPlaying = setInterval(function () {
        $('#cancion').load('sonando.php?emisora=' + station);
    }, 5000);
}


For people who only needs to destroy or stop a previous setInterval, not exactly what the question ask (jquery, song, etc)

const previousSetIntervalInstance = setInterval(myTimer, 1000);

//every 1 second update the time
function myTimer() {
  const date = new Date();
  document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}

function myStopFunction() {
  clearInterval(previousSetIntervalInstance);
}
<h3>setInterval() and clearInterval() demo</h3>
<p id="demo"></p>
<button onclick="myStopFunction()">Stop the time</button>

Initial source: https://www.w3schools.com/jsref/met_win_clearinterval.asp

When you click on stop the time is not updated anymore

Basically, you need to store the setInterval output as global variable and pass it to clearInterval

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜