如何在JavaScript中停止计时器?

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

我想通过单击按钮停止计时器,但是我找不到确切的方法.我试图通过 clearInterval()停止计时器,但不确定是否调用正确.

I want to stop a timer by clicking a button but I can't find the exact way. I've tried to stop a timer by clearInterval() but I'm not sure if it is called properly.

这是我的工作代码.

<html> <head> <title>Bootstrap</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="setest_style.css"> <link href="cdn.bootcss/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="cdnjs.cloudflare/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="ajax.googleapis/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> var sec = 0; function pad(val) { return val > 9 ? val : "0" + val; }; setInterval( function(){ $("#seconds").html(pad(++sec%60)); $("#minutes").html(pad(parseInt(sec/60,10))); }, 1000); function myStopFunction() { clearInterval(sec); } </script> </head> <body> <div class="quiz-time"> <div class="timer"> <span id="minutes">00</span>:<span id="seconds">00</span> </div> <button href="#" id="show-explanation" class="button1" onclick="myStopFunction()">Stop</button> </div> </body> </html>

推荐答案

将设置的间隔作为变量,然后使用清除间隔

take that set interval into a variable then use clear interval

var myInterval = setInterval( function(){ $("#seconds").html(pad(++sec%60)); $("#minutes").html(pad(parseInt(sec/60,10))); }, 1000); function myStopFunction() { clearInterval(myInterval); }

更多推荐

如何在JavaScript中停止计时器?

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

发布评论

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

>www.elefans.com

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