1

我已经尝试了几个小时来制作一个 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);
4

3 回答 3

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

于 2013-04-01T03:38:49.407 回答
0

count在每个循环中都被重置为 600。只需将其声明移到函数之外,如下所示:

var count = parseInt(document.getElementById("unixtime_coming_0").innerHTML, 10);
setInterval(function timer() {
    count = count - 1;
[...]
于 2013-04-01T03:44:49.447 回答
0

为了准确倒计时,您需要使用 new Date().getTime()。请查看此答案以了解类似问题https://stackoverflow.com/a/15635372/1523245

于 2013-04-01T04:51:33.230 回答