gpt4 book ai didi

JavaScript 秒表 SetInterval 忽略 ClearInterval

转载 作者:行者123 更新时间:2023-11-28 17:16:07 27 4
gpt4 key购买 nike

我正在制作一个秒表,在我告诉它停止或根本不停止后,setInterval 似乎会自行重新启动。

我想要的是,当我按“停止”时,setInterval 会停止循环,但会保持当前的数字,除非单击重置按钮。

const sw = {
time: 0,
reset: ()=>{
clearInterval(sw.stopWatch)
sw.time = 0
},
stop: ()=>{
clearInterval(sw.stopWatch)
console.log("stop")
},
stopWatch: ()=>{
setInterval(function(){
sw.time ++
document.getElementById("time").innerHTML = sw.time
}, 1000)
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="index.js"></script>
</head>
<body>
<div id="time">0</div>
<button onclick="sw.stopWatch()">Start</button>
<button onclick="sw.stop()">Stop</button>
<button onclick="sw.reset()">Reset</button>

</body>
</html>

最佳答案

clearInterval 采用计时器 ID,而不是函数。您尝试使用 sw.stopWatch 来调用它,它是一个函数。

相反,您需要保存 setInterval 返回的 ID 并将其传递给 clearInterval:

const sw = {
time: 0,
reset: ()=>{
clearInterval(sw.timerId)
sw.time = 0
},
stop: ()=>{
clearInterval(sw.timerId)
console.log("stop")
},
stopWatch: ()=>{
sw.timerId = setInterval(function(){
sw.time ++
document.getElementById("time").innerHTML = sw.time
}, 1000)
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="index.js"></script>
</head>
<body>
<div id="time">0</div>
<button onclick="sw.stopWatch()">Start</button>
<button onclick="sw.stop()">Stop</button>
<button onclick="sw.reset()">Reset</button>

</body>
</html>

关于JavaScript 秒表 SetInterval 忽略 ClearInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53468274/

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