如何停止计时器功能的运行? [英] How to stop a timer function from running?

查看:376
本文介绍了如何停止计时器功能的运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

代码:

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

脚本:

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小提琴: http://jsfiddle.net/58Jv5/13/

预先感谢您的帮助。

推荐答案

您需要为JavaScript提供间隔参考:

You need to give JavaScript a reference to the interval:

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

然后您可以清除它:

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

这篇关于如何停止计时器功能的运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆