George
George

Reputation: 35

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. 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.

I Tried calling the function which contains the timer after clearInterval but timer still doesn't work.

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

Upvotes: 0

Views: 122

Answers (2)

SeyyedMojtaba
SeyyedMojtaba

Reputation: 1514

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>

Upvotes: 0

Joel Mun
Joel Mun

Reputation: 81

The problem

You are not returning from gameTimer function. In order to subscribe to setInterval, you need to get the value from it. 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:

function resetFunc(){

   clearInterval(gameTimer(0))

}

this would start the timer, but at the same time clear the interval returned from 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.

Check on CodeSandbox Too

Upvotes: 2

Related Questions