倒数计时器添加额外2分钟

时间:2018-01-12 02:07:09

标签: javascript html timer

我创建了一个倒数计时器,并试图将2分钟添加到现有计时器中以延长计时器。

我的代码

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
    that = this,
    diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

$(document).ready(function() {
  var counter = 0;

  var display = document.querySelector('#time'),
    //timer = new CountDownTimer(600);
    timer = new CountDownTimer(125); // for debug
  timer.onTick(format).onTick(restart).start();

  function restart() {
    if (this.expired()) {
      alert("Expired");
    }
  }

  function format(minutes, seconds) {
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = minutes + ':' + seconds;
    if (minutes < 2) {
      if (counter == 0) {
        alert("Extending Time");
        counter++;
      }
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="time"></span> minutes

我设法触发了一个事件,在2分钟后会显示一个时间将被延长的警报,但到目前为止,我想不出任何可用于增加额外时间的方法或功能。我有什么方法可以做到这一点吗?

2 个答案:

答案 0 :(得分:1)

添加以下代码:

CountDownTimer.prototype.reset = function (duration) {
    this.duration = duration;
}

并将函数format重写为:

function format(minutes, seconds) {
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = minutes + ':' + seconds;
    if (minutes < 2) {
        if (counter == 0) {
            //alert("Extending Time");
            timer.reset(timer.duration + 120);
            counter++;
        }
    }
}

答案 1 :(得分:1)

您可以在CountDownTimer.prototype.start之前的setTimeout添加代码,如:

this.instance = setTimeout(...)

添加功能:

CountDownTimer.prototype.kill = function() { 
    clearTimeout(this.instance)
}

调用函数 kill 以永久停止计时器。