如何设置计时器的重置按钮?

问题描述

点击按钮后,我需要重置计时器。我需要重置按钮,因为用户可以多次访问计时器,但是计时器显示的是从以前使用的时间开始的计时器+计时器的当前时间。

这是其中一个带有指定按钮的计时器的片段

链接代码https://youtu.be/47KzYVBNbIs

 <script>


        
      function startTimer(duration,display) {
          var timer = duration,minutes,seconds;
          setInterval(function () {
              minutes = parseInt(timer / 60,10);
              seconds = parseInt(timer % 60,10);
    
              minutes = minutes < 10 ? "0" + minutes : minutes;
              seconds = seconds < 10 ? "0" + seconds : seconds;
    
              display.textContent = minutes + ":" + seconds;
    
              if (--timer < 0) {
                  timer = 0;
              }
    
          },1000);
         
    
          }
      
    
           
    

      function start5Timer() {
          var fiveMinutes = 60 * 5,display5 = document.querySelector('#time5');
          startTimer(fiveMinutes,display5);
    
      }
      
  
  function show5Timer() {
          document.getElementById("button").style.display = "none";
          document.getElementById("timer5").style.display = "block";
        }

    </script>
    
    <button id="button" onclick= "show5Timer(); start5Timer();">Starts and Shows Timer</button>
    
    
      <div id=timer5 style ="display:none">
          <h1><span id="time5">5:00</span></h1>
          <p>click next when the timer ends *clicking nextBtn takes them to another div,I want this to also restart the time*</p>
          <button onclick="taketoNextDiv(); #();">
          next
          </button>
      </div>

解决方法

您需要保存时间间隔返回值,以便以后使用它并删除时间间隔,然后重置计时器并重新启动它。 setInterval返回一个整数,可以在其上调用clearInterval函数。

var interval; 
function startTimer(duration,display) {
      var timer = duration,minutes,seconds;
      if(interval)
          clearInterval(interval)
      interval = setInterval(function () {
          minutes = parseInt(timer / 60,10);
          seconds = parseInt(timer % 60,10);

          minutes = minutes < 10 ? "0" + minutes : minutes;
          seconds = seconds < 10 ? "0" + seconds : seconds;

          display.textContent = minutes + ":" + seconds;

          if (--timer < 0) {
              timer = 0;
          }

      },1000);
}