gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:32:26 24 4
gpt4 key购买 nike

我创建了一个倒计时器,并尝试在现有计时器中添加 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com