繁体   English   中英

倒数计时器可增加2分钟

[英]Countdown Timer to Add extra 2 minutes

我创建了一个倒数计时器,并尝试在现有计时器中增加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++;
        }
    }
}

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

this.instance = setTimeout(...)

增加功能:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM