Home > Blockchain >  Resetting a Timer Back to 0 from Counter?
Resetting a Timer Back to 0 from Counter?

Time:08-04

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)
}

CodePudding user response:

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" />

CodePudding user response:

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>

  • Related