0

I have been googling for a solution for this problem, but many suggestions that I have found either freezes the counter or does nothing. counter.innerHTML = 0 just resumes where it left off after a second.

Here is my code:

let reset = document.getElementById('reset')
let counter = document.getElementById('counter')
let num = 0;

let timer = setInterval(countUp, 1000);
function countUp() {
    counter.innerHTML = num++
}
//Reset timer
reset.addEventListener('click', stuff) 
function stuff() {
    clearInterval(timer)
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
taram414
  • 35
  • 7
  • Does this answer your question? [How do I reset the setInterval timer?](https://stackoverflow.com/questions/8126466/how-do-i-reset-the-setinterval-timer) – Heretic Monkey Aug 04 '22 at 03:15

2 Answers2

1

What you have is mostly working, you just need to

  • clear the internal
  • reset the innerHtml to 0

let reset = document.getElementById('reset')
let counter = document.getElementById('counter')
let num = 0;

let timer = setInterval(countUp, 1000);

function countUp() {
  counter.innerHTML = num++
}

//Reset timer
reset.addEventListener('click', stuff)

function stuff() {
  counter.innerHTML = 0;
  clearInterval(timer)
}
<button id="reset">reset</button>

<div id="counter" />
davidhu
  • 9,523
  • 6
  • 32
  • 53
1

It's probably useful to put the logic that changes what you see in the page content in its own function: this will help you think about each part of the problem independently:

let resetBtn = document.getElementById('reset');
let counter = document.getElementById('counter');
let num = 0;

// Start the timer
let timer = setInterval(countUp, 1000);

// Use this to update the DOM (page content)
function updateUI () {
  counter.textContent = num;
}

function countUp () {
  // Increment the number
  num += 1;
  // Update the DOM
  updateUI();
}

function reset () {
  // Stops the interval
  clearInterval(timer);
  // Reset the number
  num = 0;
  // Update the DOM
  updateUI();
}

// Update the UI the first time (before the counter reaches 1)
updateUI();

// Add the reset functionality to the button
resetBtn.addEventListener('click', reset);
<div id="counter"></div>
<button id="reset">Reset</button>
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
  • Thanks! Most of it help. I removed clearInterval(timer), and replaced updateUI() with countUp() inside the reset function block. I also started num at -1 so the counter begins at 0. – taram414 Aug 04 '22 at 03:48