小时数不适用于秒表

时间:2013-07-16 19:36:31

标签: javascript settimeout increment stopwatch

我正在制作一个秒,分钟和小时的秒表。我希望秒表在小时数达到59后重置并重新启动。此外,当分钟达到59时,我希望时针递增。它似乎不起作用。如果你愿意,左手小时“手”将不会增加..即使我说我想要它。

请在SETTIMEOUT上注意速度“5”。我尽力测试时间。应该是“1000”。

HTML:

    <ul>

        <li id="hour-greater">0</li>
        <li id="hour-lesser">0</li>
        <li>:</li>
        <li id="min-greater">0</li>
        <li id="min-lesser">0</li>
        <li>:</li>
        <li id="sec-greater">0</li>
        <li id="sec-lesser">0</li>

    </ul>

JS:

(function() {

    var secLesser = document.getElementById("sec-lesser").value,
    secGreater = document.getElementById("sec-greater").value,
    minLesser = document.getElementById("min-lesser").value,
    minGreater = document.getElementById("min-greater").value,
    hourLesser = document.getElementById("hour-lesser").value,
    hourGreater = document.getElementById("hour-greater").value;


    function stopWatch(){
        secLesser++;
        if(secLesser > 9) {
            secLesser = 0;
            secGreater++;
        } else if(secGreater + secLesser == 14){
            secGreater = 0;
            secLesser = 0;
            minLesser++;
        } else if(minLesser > 9){
            minLesser = 0;
            minGreater++;
        } else if(minGreater + minLesser == 14){
            secGreater = 0;
            secLesser = 0;
            hourLesser++;
        } else if(hourLesser > 9){
            hourLesser = 0;
            hourGreater++;
        } else if(hourGreater + hourLesser == 14){
            alert("It's been 59 hours... leave this page!");
        } 

        document.getElementById("sec-lesser").textContent = secLesser;
        document.getElementById("sec-greater").textContent = secGreater;
        document.getElementById("min-lesser").textContent = minLesser;
        document.getElementById("min-greater").textContent = minGreater;
        document.getElementById("hour-lesser").textContent = hourLesser;
        document.getElementById("hour-greater").textContent = hourGreater;
        window.setTimeout(stopWatch, 5);
    }

    stopWatch();
})();

1 个答案:

答案 0 :(得分:1)

你所拥有的部分

} else if(minGreater + minLesser == 14){
            secGreater = 0;
            secLesser = 0;
            hourLesser++;

应该重置minGreater和minLesser而不是secGreater / secLesser。将其更改为:

} else if(minGreater + minLesser == 14){
            minGreater = 0;
            minLesser = 0;
            hourLesser++;

哦,并考虑requestAnimationFrame作为setTimeout / setInterval的更好替代方案。