本文介绍了如何停止计时器功能的运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对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小提琴: jsfiddle/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); });更多推荐
如何停止计时器功能的运行?
发布评论