super11
super11

Reputation: 476

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.

Upvotes: 1

Views: 689

Answers (2)

Vinod K
Vinod K

Reputation: 148

Try this..

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

<button onClick="clearInterval(myVar)">Stop time!</button>
<button onClick="startTimer()">Start time!</button>
<script>
var myVar;

function startTimer() {

    myVar = setInterval(myTimer, 1000);
}

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

Upvotes: 0

epascarello
epascarello

Reputation: 207501

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>

Upvotes: 5

Related Questions