The following code is a simple timer. However, clicking the timing button more than two times in a row will cause the timing to accelerate and cannot be paused (cannot be stopped~~). What is the bug hidden in it? Need a solution?
<!DOCTYPE html>
<html>
<head>
<title>
计时器
</title>
<style type="text/css">
p {
width: 400px;text-align:center;height: 500px;font-weight: 700;background-color: #ccc;font-size: 400px;margin: 0 auto;
}
</style>
</head>
<body>
<p><font color="red" size="28"></font></p>
<input type="button" value="计时开始⌚️">
<input type="button" value="计时暂停⏸️">
<script type="text/javascript">
//计时开始方法
var i = 0;
var times;
var prebtn = document.getElementsByTagName("input")[0].onclick=function()
{
times = window.setInterval(function(){
i++
document.getElementsByTagName("p")[0].innerHTML=i;
},1000);
}
//计时结束方法
var nextbtn = document.getElementsByTagName("input")[1].onclick=function()
{
var cleartimes = window.clearInterval(times);
}
</script>
</body>
</html>
Judge in the timing function
times
如果有值,直接返回;或者有值的情况下先
clearInterval
然后再重新setInterval
Clicking 2 times is equivalent to setting 2 timers, so it will be a trap.