1

I have a counter function I got it from this Answer :

  function countDown(i) {
    var int = setInterval(function () {
        document.querySelector(".count").innerHTML = "Number: " + i;
        i-- || clearInterval(int);  //if i is 0, then stop the interval
    }, 1000);
}
countDown(60);

So when it finishes counting it stops at 0;

What I'm trying to achieve when the counter stops at zero I want to reset the function to count down from 60 to 0.

Is it possible to reset the function? I'm really lost at this point

Alan
  • 13
  • 2

1 Answers1

3

The easiest way to achive this is to not stop the counter at all. Just set the value of i to 60 when it's value is 0.

function countDown(i) {
    var int = setInterval(function () {
        document.querySelector(".count").innerHTML = "Number: " + i;
        i = i > 0 ? i - 1 : 60;
    }, 1000);
}
countDown(60);
displayName
  • 986
  • 16
  • 40
  • a simple and easy solution, Brilliant! – Alan Sep 04 '18 at 00:12
  • 3
    This is a great solution, but I have two suggestions. 1- avoid using `int` as a variable. It's a [reserved keyword](https://www.w3schools.com/js/js_reserved.asp). 2- move the document selector outside the interval for efficiency. Other wise you keep scanning the dom each time. – Ibu Sep 04 '18 at 00:14