CountDown计时器 - 凌乱的函数Javascript

时间:2018-01-12 09:17:10

标签: javascript function timer countdowntimer


我有一个带有CountDown Timer功能的代码, 但我有一个问题,我无法解决 - 如果我点击按钮上的另一个时间,它会弄乱 如果它还在计算的话,我如何才能从新时间开始计算/或者不计算重复数? 为什么这样做?

  function myFunctionTimer() {
      var timeoutHandle;
      function countdown(minutes) {
          var seconds = 60;
          var mins = minutes
          function tick() {
              var counter = document.getElementById("time");
              var current_minutes = mins-1
              seconds--;
              counter.innerHTML =
              current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
              if( seconds > 0 ) {
                  timeoutHandle=setTimeout(tick, 1000);
      }
       if( seconds == 0 ) {
      window.location.reload()
      }else {
                  if(mins > 1){
                     setTimeout(function () { countdown(mins - 1); }, 1000);}}}tick();}
      countdown(1);};
 <button onclick="myFunctionTimer()">Click me</button>
 
 <div class="OfertaWazna" >Counter: <span id="time"></span></div>

1 个答案:

答案 0 :(得分:1)

您需要使超时变量可以访问myFunctionTimer,以便下次调用时清除相同的

function myFunctionTimer( ele ) {

  //attach the timer to the element
  var tickTimer = ele.tickTimer;
  if ( tickTimer )
  {
     clearTimeout( tickTimer );
  }
   // rest of the code

}

另外

  • 无需创建两个定时器,一个就足够了。只需检查最终时间值是否为0。
  • 使用addEventListener代替onclick,它不那么具有侵入性和可读性。

<强>演示

function myFunctionTimer( ele ) {
 
  //attach the timer to the element
  var tickTimer = ele.tickTimer;
  if ( tickTimer )
  {
     clearTimeout( tickTimer );
  }

  function countdown(minutes) {
    var seconds = 60;
    var mins = minutes

    function tick() {
      var counter = ele;
      var current_minutes = mins - 1
      seconds--;
      counter.innerHTML =
        current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
      if (seconds > 0) {
        ele.tickTimer = setTimeout(tick, 1000); //set the timer here
      }      
    }
    tick();
  }
  countdown(1);
}

document.querySelector( "button" ).addEventListener( "click", function(){
   myFunctionTimer( document.getElementById( "time" ) );
});
<button>Click me</button>
<div class="OfertaWazna">Counter: <span id="time"></span></div>