按下按钮时,JS Timer不启动

时间:2012-07-20 23:26:37

标签: javascript timer

我一直在看这几个小时,似乎无法理解为什么我的代码在按下按钮时没有启动计时器倒计时。非常感谢任何帮助,谢谢!

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);
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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);
}