Home > Back-end >  Resetting a setInterval with a Reset button
Resetting a setInterval with a Reset button

Time:05-20

As you can see, I've pulled together some code that invokes a setInterval call with button, and then invokes a clearInterval call with another button. What I'm struggling with is putting together a "Reset" button.

I've written some code that I've since removed that 'resets' the demo back to 0; however, when the Start button is pushed again after a Reset, it begins counting at the point that I stopped the counter last.

function myCounter() {
document.getElementById("demo").innerHTML =   c;
} 

Any help is appreciated! Apologies for my rudimentary coding knowledge/expertise. I'm a complete novice, so keep that in mind for any responses.

<p id="demo">0
 </p>
 <button onclick="myTimer = setInterval(myCounter, 1000)">
  Start counter!
 </button>
 <button onclick="clearInterval(myTimer)">
  Stop counter!
 </button>
 <script>
  var c = 0;
function myCounter() {
 document.getElementById("demo").innerHTML =   c;
}
 </script>

CodePudding user response:

You will need to do something to set var c back to 0 (and update it in the HTML).

<p id="demo">0
</p>
<button onclick="myTimer = setInterval(myCounter, 1000)">
  Start counter!
</button>
<button onclick="clearInterval(myTimer)">
  Stop counter!
</button>
<button onclick="reset()">
  Reset counter!
</button>
<script>
  var c = 0;

  function myCounter() {
    document.getElementById("demo").innerHTML =   c;
  }

  function reset() {
    c = 0
    document.getElementById("demo").innerHTML = 0;
  }
</script>

CodePudding user response:

Add demo.innerHTML = 0; will work your code as you intended.

let c = 0;
let myTimer;
const demo = document.getElementById("demo")

function start() {
  myTimer = setInterval(myCounter, 1000)
}

function myCounter() {
 demo.innerHTML =   c;
}

function reset() {
  clearInterval(myTimer)
  demo.innerHTML = 0;
}
<p id="demo">
0
</p>
<button onclick="start()">
  Start counter!
</button>
<button onclick="reset()">
  Stop counter!
</button>

  • Related