0

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 = "0";
} 

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>
codeshiba
  • 15
  • 4
  • have a look to https://stackoverflow.com/questions/71174215/how-to-save-time-value-in-dynamically-created-li-to-input-box-with-javascript/71182048#71182048 – Mister Jojo May 19 '22 at 23:58

2 Answers2

0

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>
Dali
  • 571
  • 1
  • 4
  • 16
0

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>
  • Thanks for this solution, worked just like I was aiming for. A follow up question, if you know it - is there any way to coerce the value (that is counting up) created by myTimer? I think that may be a bit high level for my experience, but I would like to use that value in other dynamic math calculations, if possible. – codeshiba May 20 '22 at 00:00