gpt4 book ai didi

JavaScript 计时器从某个时间开始倒计时数小时

转载 作者:行者123 更新时间:2023-11-30 16:53:54 25 4
gpt4 key购买 nike

我已经创建了一个倒数计时器。问题是,我希望它从午夜时钟 00:00:00 倒计时到时钟 17:00:00

我已经让计时器从 17 小时 00 分 00 秒 开始倒计时,这很有用,但我需要一种方法来从 00:00:00 开始计时17 小时开始呈现。

这是我的JS代码

    function startTimer(duration, display) {
var start = Date.now(),
diff,
hours,
minutes,
seconds;

function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);

// Setting and displaying hours, minutes, seconds
hours = (diff / 360) | 0;
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;

hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;

display.textContent = hours + ":" + minutes + ":" + seconds;

if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 17:00:00 not 16:59:59
start = Date.now() + 1000;
}
};
// don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var timeLeft = 3600 * 17,
display = document.querySelector('#time');
startTimer(timeLeft, display);
};

这是我的 HTML 代码:

<div>Order by: <span id="time"></span> for Next Day Delivery.</div>

我的想法是获取 timeLeft = 3600 * 17 并消除 diff。

最佳答案

这是您更正的代码:保存当天 17 点的时间戳(如果我们在 17 点之后是第二天)并将其与当前时间戳进行比较会更容易。要计算剩余的小时数,您必须将秒数除以 3600 (60*60) 而不是 360

function startTimer(display) {
var date = new Date();
var h17 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 17);
if(date.getHours() >= 17) {
h17.setDate(h17.getDate()+1);
}
h17 = h17.getTime();
var diff,
hours,
minutes,
seconds;

function timer() {
diff = (((h17 - Date.now()) / 1000) | 0);

// Setting and displaying hours, minutes, seconds
hours = (diff / 3600) | 0;
minutes = ((diff % 3600) / 60) | 0;
seconds = (diff % 60) | 0;

hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;

display.textContent = hours + ":" + minutes + ":" + seconds;
};
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var timeLeft = 3600 * 17,
display = document.querySelector('#time');
startTimer(display);
};
<div>Order by: <span id="time"></span> for Next Day Delivery.</div>

jsFiddle

PS :我没有测试功能是否在 17 小时后正常工作,但应该可以

关于JavaScript 计时器从某个时间开始倒计时数小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30078870/

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