gpt4 book ai didi

javascript - 以小时/分钟/秒为单位转换 JavaScript 倒计时秒数

转载 作者:行者123 更新时间:2023-12-04 17:07:32 26 4
gpt4 key购买 nike

我必须更改以下代码,以便函数 createTimer 获得两个参数(小时和分钟)并且输出格式必须为“时分秒”,我正在努力解决这个问题。

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

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

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

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

function startTimer() {
var timer = new createTimer({
seconds: 10,
onUpdateStatus: function (seconds) {
document.getElementById("timer").innerHTML = seconds + " seconds";
},
onCounterEnd: function () {
document.getElementById("timer").innerHTML = "Time's up";
},
});
timer.start();
}

最佳答案

你需要不断减少秒数,并使用多个 if 条件将分钟和小时减一。

function createTimer(hours, minutes) {
var timer,
instance = this,
seconds = 0,
hours = hours,
minutes = minutes,
updateStatus = onUpdateStatus || function() {},
counterEnd = onCounterEnd || function() {};

function onUpdateStatus(h, m, seconds) {
document.getElementById("timer").innerHTML = h + " hours " + m + " minutes " + seconds + " seconds";
}

function onCounterEnd() {
document.getElementById("timer").innerHTML = "Time's up";
}

function decrementCounter() {
updateStatus(hours, minutes, seconds);
if (hours === 0 && minutes === 0 && seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
if (minutes < 0) {
hours--;
minutes = 59;
}
}

}

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

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

function startTimer() {
var timer = new createTimer(0,1);
timer.start();
}

startTimer()
<div id="timer"></div>

关于javascript - 以小时/分钟/秒为单位转换 JavaScript 倒计时秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70233040/

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