gpt4 book ai didi

javascript - 如何自动倒计时,点击javascript继续倒计时

转载 作者:行者123 更新时间:2023-12-03 10:30:10 25 4
gpt4 key购买 nike

我想要一个简单的倒计时,一个在时间结束时自动开始的倒计时,以及一个在我单击按钮时开始的倒计时。

我一直在尝试解决这个问题,我编写了下面的代码,我无法同时执行这两个选项,我设法执行了以下代码:当倒计时完成时,它会再次统计,请参阅代码片段

我无法做到这一点,这是我的代码:

JS

var i = 1;

function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};

function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
instance.stop();
counterEnd();
return;
}
seconds--;
}

this.start = function () {
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};

this.stop = function () {
clearInterval(timer);
};
}

var myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){$('#countdown').html(sec);}, // callback for each second
onCounterEnd: function(){
myCounter.start();
} // final action
});

myCounter.start();

$("#button").click(function() {
myCounter.start();
});

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="countdown"></p>
<button type="button" id="button">restart</button>

你知道如何解决这个问题吗?

谢谢

最佳答案

试试这个,你必须有一个 $(document).ready 函数。

var i = 1;

function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};

function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
instance.stop();
counterEnd();
return;
}
seconds--;
}

this.restart = function() {
seconds = options.seconds;
}

this.start = function () {
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};

this.stop = function () {
clearInterval(timer);
};
}

$(document).ready(function() {
var myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){
$('#countdown').html(sec);
}, // callback for each second
onCounterEnd: function(){
myCounter.start();
} // final action
});

myCounter.start();

$("#button").on('click', function() {
myCounter.restart();
});
});

Plunker demo

关于javascript - 如何自动倒计时,点击javascript继续倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29255321/

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