gpt4 book ai didi

javascript - 如何在 JavaScript 中停止计时器?

转载 作者:行者123 更新时间:2023-11-28 11:20:57 25 4
gpt4 key购买 nike

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

这是我的工作代码。

<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="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/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>

最佳答案

将设置的间隔放入变量中,然后使用清除间隔

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

关于javascript - 如何在 JavaScript 中停止计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49425137/

25 4 0
文章推荐: Javascript:如何将输入打印到按类选择的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com