-3

I have this working code and I would like the timer to stop at 0 instead of continuing with negative numbers

  function animateValue(id) {
  var obj = document.getElementById(id);
  var current = +localStorage.getItem('counter') || +obj.innerHTML;
  obj.innerHTML = current;
  function decrement(){
    --current;
    obj.innerHTML = current;
    localStorage.setItem('counter', current);
    if(current != 0){
        setTimeout(decrement, (Math.floor(Math.random()*11) + 10) * 1000);
    }
  }
  setTimeout(decrement, (Math.floor(Math.random()*11) + 10) * 2000);
}

animateValue('counter');

i tried to add but to no avail

if (seconds === 0) {
    stop();
}
  • 3
    Does this answer your question? [When using setTimeout do you have to clearTimeout?](https://stackoverflow.com/questions/7391567/when-using-settimeout-do-you-have-to-cleartimeout) – Alon Eitan Sep 29 '21 at 13:08
  • https://stackoverflow.com/questions/40632567/how-to-stop-timer-after-reaching-zero – Andrew Sep 29 '21 at 13:11

3 Answers3

1

Wrap the code inside decrement in an if statement like so:

function decrement() {
    if (current > 0) {
        --current;
        obj.innerHTML = current;
        localStorage.setItem('counter', current);
        setTimeout(decrement, (Math.floor(Math.random()*11) + 10) * 1000);
    }
}
Vid
  • 440
  • 4
  • 10
0

If you use setInterval for it, you can deactivate it with clearInterval.

It will work at least that I think

0

For this bit you tried,

   if (seconds === 0) {
    stop();
}

Is this not meant to be

if (current <= 0) {
    stop(); //I assume you have some code to stop it
}