繁体   English   中英

如何为计时器制作重置按钮?

[英]How do you make a reset button for a timer?

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

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

代码链接: http://jsfiddle.net/bw2dfkyu/

 <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 返回一个 integer,您可以在其上调用 clearInterval function。

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM