JS练习_在网页中制作一个秒表
要求:在网页中制作一个秒表(开始功能、停止功能、重置)
预览:
源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计时器</title>
</head>
<body>
<button class="start">开始</button>
<button class="pause">暂停</button>
<button class="reset">结束</button>
<h1 class="time">10:9</h1>
<script>
let start = document.querySelector(".start");
let pause = document.querySelector(".pause");
let reset = document.querySelector(".reset");
let time = document.querySelector(".time");
let seconds = 0;
let ms = 0;
let timer = null;
time.innerHTML = `${seconds}:${ms}`;
start.onclick = function (){
// 为了防止事件函数导致计时器执行的次数越多,数越快
clearInterval(timer);
timer = setInterval(() =>{
if (ms ===9){
++seconds;
ms = 0;
}
++ms;
time.innerHTML = `${seconds}:${ms}`;
},100)
}
pause.onclick = function (){
clearInterval(timer);
}
reset.onclick = function (){
seconds = 0;
ms = 0;
time.innerHTML = `${seconds}:${ms}`;
}
</script>
</body>
</html>
把最实用的经验,分享给最需要的读者,希望每一位来访的朋友都能有所收获!