【发布时间】:2021-01-29 19:23:25
【问题描述】:
我想创建一个每周重置的计数器,我发现一个或多或少有效的代码,但是当它变为 0 时,它显示为负数.... -1d -1h -2m -5s
<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 29, 2021 20:21:0").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
//document.getElementById("demo").innerHTML = "GAME DAY";
if(distance < - 1000 * 60 * 60* 24){ // if its past the "game day"
// reset timer to next week
countDownDate += 1000 * 60 * 60 * 24 * 7
}
}
}, 1000);
</script>
<span id="demo"></span>
【问题讨论】:
-
这个计数器应该从什么时候到什么时候倒计时?如果您希望计数器每周重置,为什么要硬编码
Jan 29, 2021 20:21:0?距离 -
我只是在测试,我想数一下,从周五到周五
-
您希望它从每周五晚上 8:21 开始倒计时,并以 h:m:s 显示到下周五晚上 8:21 的剩余时间?
-
正确,正好是8:00,每周五,到0的时候,重新开始计数,直到下周五
-
好的,感谢您的澄清。您希望何时显示“比赛日”?我猜晚上 8 点后的一两个小时应该会显示这个(游戏是实时的)还是应该立即开始下周的倒计时?
标签: javascript html counter