setInterval与clearInervar
实现秒表功能
<button class="start">开始</button> <button class="stop">暂停</button> <button class="end">结束</button> <h1 class="time">10:9</h1> <script> let start = document.querySelector('.start') let stop = document.querySelector('.stop') let end = document.querySelector('.end') let time = document.querySelector('.time') let seconds = 0 let ms = 0 time.innerHTML = `${seconds}:${ms}` let timer = null // 开启计时器 start.onclick = function () { // 开始的时候删掉之前的计时器并重新开启一个计时器 防止多次开启计时器越来越快的情况 clearInterval(timer) timer = setInterval(() => { // 设置进制 if (ms === 9) { seconds++ ms = 0 } ms++ time.innerHTML = `${seconds}:${ms}` }, 100) } // 暂停计时器 stop.onclick = function () { clearInterval(timer) } // 结束计时器 end.onclick = function () { seconds = 0 ms = 0 time.innerHTML = `${seconds}:${ms}` } </script>