javascript - 倒计时器可额外增加 2 分钟

标签 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 分钟后将显示时间将延长的警报,但到目前为止,我想不出任何可以用来添加额外时间的方法或函数。有什么办法可以做到这一点吗?

最佳答案

添加代码如下:

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

关于javascript - 倒计时器可额外增加 2 分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48218566/

相关文章:

javascript - ReactJs 在按钮单击时更改文本问题

javascript - 在 Jasmine 中,如何删除一个被监视的方法?

jQuery Div 旋转?

php - 浏览器如何决定何时再次请求缓存文件?

Java 执行某事 15 秒,然后 5 秒后执行其他操作

WPF 调度程序计时器滴答卡住我的应用程序

java - 计时器导致 Tomcat 服务器出现问题

javascript - 防止 window.onload 被覆盖

javascript - jQuery "chosen": conflict with 'selected' attribute in option tag

html - 菜单绝对位置 <ul> 的边距