super11 super11 - 5 months ago 20
Javascript Question

Why does clearInterval works only once?

I have this example:

<p id="test"></p>

<button onClick="clearInterval(myVar)">Stop time!</button>
<button onClick="setInterval(myTimer, 1000)">Start time!</button>

<script>

var myVar = setInterval(myTimer, 1000);

function myTimer() {
var d = new Date();
document.getElementById('test').innerHTML = d.toLocaleTimeString();
}

</script>


When I click "Stop time!" for the first time it works as it should, but after I click "Start time!" I cannot stop timer anymore. Why exactly is this happening and how to fix this?

Thanks.

Answer

Look at this code

<button onClick="setInterval(myTimer, 1000)">Start time!</button>

It does not work because you do not set the new timer to the variable. It does not know the new value should be set there.

Not a fan of inline code, but this would work

<button onClick="myVar = setInterval(myTimer, 1000)">Start time!</button>

A better design would be something like this:

(function() {

  var timer;

  function myTimer() {
    var d = new Date();
    document.getElementById('test').innerHTML = d.toLocaleTimeString();
  }

  function startTimer() {
    stopTimer(); //make sure timer is not already running
    timer = setInterval(myTimer, 1000); //start new timer
  }

  function stopTimer() {
    if (timer) clearInterval(timer);
    timer = null;
  }

  document.getElementById("stop").addEventListener("click", stopTimer);
  document.getElementById("start").addEventListener("click", startTimer);

  startTimer();

}());
<p id="test"></p>

<button id="stop">Stop time!</button>
<button id="start">Start time!</button>

Comments