【发布时间】:2019-04-27 08:10:05
【问题描述】:
我正在制作秒表,但在我告诉它停止或根本不停止后,setInterval 似乎正在自行重新启动。
我想要的是,当我按下 Stop 时,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>
【问题讨论】:
-
setInterval()返回一个计时器 ID,您需要在clearInterval调用中使用它。
标签: javascript