简体   繁体   English

Javascript:setInterval停止使用clearInterval时的计时器无法再次重新启动它

[英]Javascript : setInterval Timer when stop using clearInterval can't restart it again

I'm working on Timer of hrs seconds minutes. 我正在使用小时秒分钟计时器。 I use setInterval for start it. 我使用setInterval启动它。 but when click on button to restart the timer it doesn't work again. 但是点击按钮重新启动计时器后,它将不再起作用。 The button suppose to clear the timer ( clearInterval ), then restart it again. 该按钮应该清除计时器(clearInterval),然后重新启动它。

I Tried calling the function which contains the timer after clearInterval but timer still doesn't work. 我尝试在clearInterval之后调用包含计时器的函数,但是计时器仍然无法正常工作。

Timer Code 计时器代码

function gameTimer(intervalTime){
    var input = {
        hours: 0,
        minutes: 0,
        seconds: 0
    };

    var timestamp = new Date(input.hours, input.minutes, input.seconds);

    var interval = intervalTime;

    setInterval(function () {
        timestamp = new Date(timestamp.getTime() + interval * 1000);
        document.querySelector('.countdown2').innerHTML = timestamp.getHours() + 'h:' 
        + timestamp.getMinutes() + 'm:' + timestamp.getSeconds() + 's';
    }, Math.abs(interval) * 1000);

}
gameTimer(1);

reset function 重置功能

 function resetFunc(){

   clearInterval(gameTimer(0))


}
let reset = document.getElementById('restart');
reset.addEventListener('click', resetFunc);

after this function i call the timer function again to restart the timer again but it's not working 此功能后,我再次调用计时器功能以再次重新启动计时器,但是它不起作用

gameTimer(1);

The problem 问题

You are not return ing from gameTimer function. 您没有从gameTimer函数return In order to subscribe to setInterval , you need to get the value from it. 为了订阅setInterval ,您需要从中获取值。 So the code would go: 所以代码会去:

function gameTimer(intervalTime){
    var input = {
        hours: 0,
        minutes: 0,
        seconds: 0
    };

    var timestamp = new Date(input.hours, input.minutes, input.seconds);

    var interval = intervalTime;

    // here!!
    return setInterval(function () {
        timestamp = new Date(timestamp.getTime() + interval * 1000);
        document.querySelector('.countdown2').innerHTML = timestamp.getHours() + 'h:' 
        + timestamp.getMinutes() + 'm:' + timestamp.getSeconds() + 's';
    }, Math.abs(interval) * 1000);

}

And your resetFunc has a problem too: 而且您的resetFunc也有问题:

function resetFunc(){

   clearInterval(gameTimer(0))

}

this would start the timer, but at the same time clear the interval returned from gameTimer . 这将启动计时器,但同时清除gameTimer返回的间隔。 So in essence it would do just nothing. 因此,从本质上讲,它什么也不做。

The answer 答案

So a complete answer would go like this: 因此,完整的答案将如下所示:

<html>
  <head>
    <script>
        window.onload = function(){

          let isTimerRunning = false
          let intervalRef

          function gameTimer(intervalTime){
              var input = {
                  hours: 0,
                  minutes: 0,
                  seconds: 0
              };

              var timestamp = new Date(input.hours, input.minutes, input.seconds);

              var interval = intervalTime;

              // here!!
              return setInterval(function () {
                console.log('hey')
              }, Math.abs(interval) * 1000);

          }

          function toggleTimer(interval){
            if (isTimerRunning){
              isTimerRunning = false
              clearInterval(intervalRef)
            }
            else{
              isTimerRunning = true
              intervalRef = gameTimer(interval)
            }
          }

          let reset = document.getElementById('restart');
          reset.addEventListener('click', function(){toggleTimer(1)});
        }
    </script>
  </head>
  <body>
    <button id = 'restart'>
      toggle
    </button>
  </body>
</html>

Note that I have simplified the logic in your callback for setInterval . 请注意,我已经简化了setInterval的回调逻辑。

Check on CodeSandbox Too 也检查CodeSandbox

 var interval, intervalTime2 = 1; function gameTimer(intervalTime){ if (interval){ clearInterval(interval); }; intervalTime2 = intervalTime; var input = { hours: 0, minutes: 0, seconds: 0 }; var timestamp = new Date(input.hours, input.minutes, input.seconds); interval = setInterval(function () { timestamp = new Date(timestamp.getTime() + intervalTime * 1000); document.querySelector('.countdown2').innerHTML = timestamp.getHours() + 'h:' + timestamp.getMinutes() + 'm:' + timestamp.getSeconds() + 's'; }, Math.abs(intervalTime) * 1000); } gameTimer(1); function resetFunc(){ gameTimer(intervalTime2); } let reset = document.getElementById('restart'); reset.addEventListener('click', resetFunc); 
 <span class="countdown2"></span> <button id="restart">Restart</button> 

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

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