Search code examples
javascriptintervalscountdown

Basic Javascript Countdown


Good day fellow developers. Please entertain what must seem like a very simple question: I have a basic countdown with the intent of counting down to 5 and loops continually.

var countDownDiv = document.getElementById('countDown');
window.setInterval(intervalCountDown, 1000);
function intervalCountDown() {
  var counter = 5;
  countDownDiv.innerHTML = counter--;
}

The problem is that it's not counting down, for what reason I don't know. Here is a fiddle I've created if that helps.


Solution

  • You redefine your counter every time countDown called.
    To prevent this, you should define variable in outer scope.

    var countDownDiv = document.getElementById('countDown');
    window.setInterval(intervalCountDown, 1000);
    var counter = 5;
    function intervalCountDown() {
      countDownDiv.innerHTML = counter--;
    }
    <span id="countDown"></span>

    You can also create something more reusable:

        function countDown(from, time, el) {
          el.innerHTML = from;
          var i = setInterval(tick, time);
          function tick() {
            el.innerHTML = --from;
            if (from <= 0) clearInterval(i);
          }
        }
    
    countDown(100, 1000, document.getElementById('c1'));
    countDown(10, 5000, document.getElementById('c2'));
    <span id="c1"></span><hr/>
    <span id="c2"></span>