我一直在努力制作一个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);
答案 0 :(得分:2)
定义命名函数不会返回任何内容。您必须在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
致电{{1}}。
答案 1 :(得分:0)
count
重置为600。只需将其声明移到函数之外,如下所示:
var count = parseInt(document.getElementById("unixtime_coming_0").innerHTML, 10);
setInterval(function timer() {
count = count - 1;
[...]
答案 2 :(得分:0)
要准确倒计时,您需要使用新的Date()。getTime()。有关类似问题https://stackoverflow.com/a/15635372/1523245
,请查看此答案