SetInterval and clearInervar realize stopwatch function

setInterval与clearInervar

Realize the stopwatch function

  <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 ()         // Set base       timer = setInterval(() => {       clearInterval(timer)       { // Delete the previous timer at the beginning and restart a timer to prevent the situation that the timer is started multiple times to get faster and faster




        if (ms === 9) {           seconds++           ms = 0         }         ms++         time.innerHTML = `${seconds}:${ms}`       }, 100)     }     // pause timer     stop.onclick = function () {       clearInterval( timer)     }     // end timer     end.onclick = function () {       seconds = 0       ms = 0       time.innerHTML = `${seconds}:${ms}`     }   </script>


















 

Guess you like

Origin blog.csdn.net/qq_19820589/article/details/131038903