如何停止计时器function的运行?
我对js有点新鲜,并且一直试图弄清楚当我点击按钮时如何停止运行此function。 我尝试使用clearInterval,但我不确定我是否正确使用它。 有人可以看看这个代码并指出我正确的方向吗?
码:
脚本:
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提供间隔的引用:
var t = setTimeout(function() { timer(counter + 1); }, 3000);
然后你可以这样清除它:
$("#stop").click(function () { clearTimeout(t); });