Javascript 如何停止运行计时器功能?

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

How to stop a timer function from running?

javascriptjqueryclearinterval

提问by isognomon

I'm a bit new to js and have been trying to figure out how to stop this function from running when I click on a button. I tried using clearInterval but I am not sure I am doing it properly. Can someone take a look at this code and point me in the right direction?

我对 js 有点陌生,一直试图弄清楚如何在单击按钮时阻止此函数运行。我尝试使用 clearInterval 但我不确定我是否正确使用它。有人可以看看这段代码并指出我正确的方向吗?

Code:

代码:

<div><h1 id="target"></h1></div>
<button id="stop">Stop</button>?

Script:

脚本:

var arr = [ "one", "two", "three"];

(function timer(counter) {
     var text = arr[counter];

    $('#target').fadeOut(500, function(){ 
        $("#target").empty().append(text).fadeIn(500);
    });

    delete arr[counter];
    arr.push(text);

    setTimeout(function() {
        timer(counter + 1);
    }, 3000);

    $("#stop").click(function () {
       clearInterval(timer);
    });

})(0);

setInterval(timer);

JS Fiddle: http://jsfiddle.net/58Jv5/13/

JS小提琴:http: //jsfiddle.net/58Jv5/13/

Thanks in advance for your help.

在此先感谢您的帮助。

回答by Chris Sobolewski

You need to give JavaScript a reference to the interval:

你需要给 JavaScript 一个区间的引用:

var t = setTimeout(function() {
    timer(counter + 1);
}, 3000);

Then you can clear it like so:

然后你可以像这样清除它:

$("#stop").click(function () {
   clearTimeout(t);
});