gpt4 book ai didi

Javascript秒倒计时

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

我已经尝试了几个小时来制作一个 javascript 函数,该函数将以秒为单位输入时间并提供倒计时。出于某种原因,它只是在第一秒后拒绝倒计时,我不明白为什么不这样做。

这是我的 HTML:

<span style="display:none;" id="unixtime_coming_0">600</span><span onload='timer()' id="timer_coming_0"></span>

这是我的 javascript:

setInterval(function timer() {
var count = document.getElementById("unixtime_coming_0").innerHTML;
count = count - 1;
if (count <= 0) {
clearInterval(counter);
return;
}
var days = Math.floor(count / 86400);
var hours = Math.floor(count / 3600) % 24;
var minutes = Math.floor(count / 60) % 60;
var seconds = count % 60;
document.getElementById("timer_coming_0").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s"; // watch for spelling
}, 1000);

最佳答案

定义命名函数不返回任何内容。您必须在 setInterval 之外定义它:

var counter = setInterval(timer, 1000);

function timer() {
var unixtime = document.getElementById("unixtime_coming_0");
var count = parseInt(unixtime.innerHTML, 10);
unixtime.innerHTML = count - 1;

if (count < 1) {
clearInterval(counter);
return;
}

var days = Math.floor(count / 86400);
var hours = Math.floor(count / 3600) % 24;
var minutes = Math.floor(count / 60) % 60;
var seconds = count % 60;

document.getElementById("timer_coming_0").innerHTML= days + "d " + hours + "h " + minutes + "m " + seconds + "s"; // watch for spelling
}

我会完全摆脱 setInterval。只需在 timer 本身内部通过 setTimeout 调用 timer

关于Javascript秒倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15737292/

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