Search code examples
javascripttimercountdowncountdowntimer

Countdown timer not stopping at 0


For some reason, my timer does not stop when the time reaches 0. JSFiddle. Here is the constructor for the countdown timer I made:

var Timer = function(opts) {
  var self = this;

  self.opts     = opts || {};
  self.element  = opts.element || null;
  self.minutes  = opts.minutes || 0;
  self.seconds  = opts.seconds || 30;

  self.start = function() {
    self.interval = setInterval(countDown, 1000);
  };

  self.stop = function() {
    clearInterval(self.interval);
  };

  function countDown() {
    if (self.minutes == 0 && self.seconds == 0) {
      self.stop();
    }

    self.seconds--;

    if (self.seconds <= 0) {
      self.seconds = 59;
      self.minutes--;
    }

    if (self.seconds <= 9) { self.seconds = '0' + self.seconds; }

    self.element.textContent = self.minutes + ' : ' + self.seconds;
  }
};

and here is my usage:

HTML:

<div id="timer"></div>

JavaScript:

var myTimer = new Timer({
  minutes: 0,
  seconds: 10,
  element: document.querySelector('#timer')
});

myTimer.start();

Solution

  • Change your countdown function to

    function countDown() {
        self.seconds--; //Changed Line
        if (self.minutes == 0 && self.seconds == 0) {
          self.stop();
        }
    
        if (self.seconds < 0) { //Changed Condition. Not include 0
          self.seconds = 59;
          self.minutes--;
        }
    
        if (self.seconds <= 9) { self.seconds = '0' + self.seconds; }
    
        self.element.textContent = self.minutes + ' : ' + self.seconds;
      }
    

    http://jsfiddle.net/8d5LLeoa/3/