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

iso*_*mon 5 javascript jquery clearinterval

我对js有点新鲜,一直试图弄清楚如何在点击按钮时停止运行此功能.我尝试使用clearInterval,但我不确定我是否正确使用它.有人可以看一下这段代码并指出我正确的方向吗?

码:

<div><h1 id="target"></h1></div>
<button id="stop">Stop</button>?
Run Code Online (Sandbox Code Playgroud)

脚本:

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);
Run Code Online (Sandbox Code Playgroud)

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

在此先感谢您的帮助.

Chr*_*ski 12

您需要为JavaScript提供间隔的引用:

var t = setTimeout(function() {
    timer(counter + 1);
}, 3000);
Run Code Online (Sandbox Code Playgroud)

然后你可以这样清除它:

$("#stop").click(function () {
   clearTimeout(t);
});
Run Code Online (Sandbox Code Playgroud)