倒数计时器不会停在0

时间:2015-09-17 04:41:08

标签: javascript timer countdown countdowntimer

出于某种原因,当时间达到0时,我的计时器不会停止。JSFiddle。这是我制作的倒数计时器的构造函数:

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

这是我的用法:

HTML:

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

JavaScript的:

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

myTimer.start();

2 个答案:

答案 0 :(得分:2)

将倒计时功能更改为

var obj = FindNewPointPosition(400,4200,400,4200); - new position 417. 425

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

答案 1 :(得分:2)

您只需稍微重新排列倒计时功能即可。当它命中检查零值的代码时,它永远不会为零。以下代码有效。

function countDown() {

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

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

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