Javascript 销毁之前的 setInterval

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4730734/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:49:27  来源:igfitidea点击:

Destroy previous setInterval

javascript

提问by Eric Fortis

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?

我想要一个函数来设置 Ajax 和重新加载计时器。下面的代码不会破坏之前的函数调用计时器,所以每次调用它时我都会得到另一个计时器。如何销毁以前的计时器?

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

回答by Kyle Wild

You need to store your timer reference somewhere outside of local scope (this essentially means declaring it with varoutside of the function). Then, clear it with clearInterval:

您需要将计时器引用存储在本地范围之外的某处(这实际上意味着var在函数外部声明它)。然后,使用以下命令清除它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);
}

回答by tobyodavies

clearInterval

清除间隔

clearInterval(prevNowPlaying);

clearInterval(prevNowPlaying);

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

您还需要在尝试取消的范围内从以前的调用中进行 prevNowPlaying

回答by gsnedders

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);
}