gpt4 book ai didi

javascript - 我怎样才能在javascript中停止计时器?

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

我希望当用户点击提交时计时器停止
当我添加 clearInterval 时出现错误

我的代码:

  <html>
<body>
<button onclick="myStopFunction()">submit</button>
<div><span id="time">01:00</span> minutes!</div>
<script type="text/javascript">



function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
var handle = setInterval(function() {
minutes = parseInt(timer / 60, 10) //10 the ten system
seconds = parseInt(timer % 60, 10);
display.textContent = minutes + ":" + seconds;


}

function myStopFunction() {
clearInterval(myVar);
}

最佳答案

您应该将 IntervalHandle 置于 startTimer 范围之外。创建闭包(如下所示)是一种很好的做法,以免用不需要公开的变量污染全局范围。

请记得调用startTimer。

您可以有如下解决方案:

<html>
<body>
<button onclick="myStopFunction()">submit</button>
<div><span id="time">01:00</span> minutes!</div>
<script type="text/javascript">
(function() { //create closure to not polute global scope
var intervalHandle;

function startTimer(duration, display) {
var timer = duration,
minutes, seconds;

//assign interval handle to outer scope
intervalHandle = setInterval(function() {
minutes = parseInt(timer / 60, 10); //10 the ten system
seconds = parseInt(timer % 60, 10);
display.textContent = minutes + ":" + seconds;
}, timer);
}

function myStopFunction() {
clearInterval(intervalHandle);
}

// export functions to global scope
window.startTimer = startTimer;
window.myStopFunction = myStopFunction;
})();
</script>
</body>
</html>

黑客快乐!

关于javascript - 我怎样才能在javascript中停止计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41299512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com