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

编程入门 行业动态 更新时间:2024-10-28 06:29:22
本文介绍了如何停止计时器功能的运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对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); });

更多推荐

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

本文发布于:2023-11-06 17:08:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564286.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!