0

我已经看了几个小时,似乎无法理解为什么我的代码在按下按钮时没有启动计时器倒计时。任何帮助将不胜感激,谢谢!

HTML

<div id="timerHours">00</div>
<div id="timerMins">00</div>
<div id="timerSecs">00</div>
<input type="button" value="Start" onclick="startTimer()"/>

JavaScript

var t;
var timerDefault = new Date();
timerDefault.setHours(0, 0, 0);

function setTimer(){
    var element = document.getElementById("timerHours");
    hours = parseFloat(element.innerHTML);
    element = document.getElementById("timerMins");
    minutes = parseFloat(element.innerHTML);
    element = document.getElementById("timerSecs");
    seconds = parseFloat(element.innerHTML);
    timerDefault.setHours(hours, minutes, seconds);
}

function startTimer() {
    setTimer();
    var h = timerDefault.getHours();
    var m = timerDefault.getMinutes();
    var s = timerDefault.getSeconds();
    h = (h < 10) ? "0" + h : h;
    m = (m < 10) ? "0" + m : m;
    s = (s < 10) ? "0" + s : s;
    document.getElementById("timerHours").innerHTML = h;
    document.getElementById("timerMins").innerHTML = m;
    document.getElementById("timerSecs").innerHTML = s;
    timerDefault.setSeconds(timerDefault.getSeconds() - 1);
    if (h == 0 && m == 0 && s == 0) clearTimeout(t)
    t = setTimeout(startTimer, 1000);
}
4

2 回答 2

1

您的“startTimer()”例程始终调用“setTimer()”,它根据 HTML 元素的内容(重新)初始化该 Date 对象。然后,该例程将秒数减 1,但它从不更新 HTML。因此,下次计时器关闭时,Date 实例(“timerDefault”)将重置为 00:00:00。

于 2012-07-20T23:37:05.853 回答
0

通过对您的代码进行一些更改,您可以看到它倒计时了一点。

<div id="timerHours">00</div>
<div id="timerMins">00</div>
<div id="timerSecs">50</div>
<input type="button" value="Start" onclick="startTimer()"/>


var t;
var timerDefault = new Date();
timerDefault.setHours(0, 0, 0);

function setTimer(){
    var element = document.getElementById("timerHours");
    hours = parseFloat(element.innerHTML);
    element = document.getElementById("timerMins");
    minutes = parseFloat(element.innerHTML);
    element = document.getElementById("timerSecs");
    seconds = parseFloat(element.innerHTML);
    timerDefault.setHours(hours, minutes, seconds);
}

function startTimer() {
    setTimer();
    timerDefault.setSeconds(timerDefault.getSeconds() - 1);
    var h = timerDefault.getHours();
    var m = timerDefault.getMinutes();
    var s = timerDefault.getSeconds();
    console.log("Hi! " + h + " " + m + " " + s);
    h = (h < 10) ? "0" + h : h;
    m = (m < 10) ? "0" + m : m;
    s = (s < 10) ? "0" + s : s;
    document.getElementById("timerHours").innerHTML = h;
    document.getElementById("timerMins").innerHTML = m;
    document.getElementById("timerSecs").innerHTML = s;
    if (h == 0 && m == 0 && s == 0) clearTimeout(t)
    t = setTimeout(startTimer, 1000);
}
于 2012-07-20T23:54:04.600 回答