首页 > 解决方案 > 秒表 - 在单击启动计时器 onclick 处理程序之前将经过的时间保持为零

问题描述

秒表 - 在单击启动计时器 onclick 处理程序之前将经过的时间保持为零

嗨,我一直在为面试测试制作 Javascript 秒表。我有一个问题,即当浏览器加载时计时器会自动启动。我尝试编辑 add() 函数的“if”语句,但没有任何乐趣。谁能帮我?

var h1 = document.getElementsByTagName('h1')[0],
    start = document.getElementById('start'),
    stop = document.getElementById('stop'),
    clear = document.getElementById('clear'),
    milli = 0, seconds = 0, minutes = 0, hours = 0,
    t;

function add() { 
    milli += 10;
    if (milli >= 1000) {
        milli = 0;
        seconds++;
        if (seconds >= 60) {
            seconds = 0;
            minutes++;
            if (minutes >= 60) {
                minutes = 0;
                hours++;
            }
        }
    }
    
    h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds) + "." + (milli > 90 ? milli : "0" + milli);

    timer();
}

function timer() {
    t = setTimeout(add, 10);
}
timer();


/* Start button */
start.onclick = timer;

/* Stop button */
stop.onclick = function() {
    clearTimeout(t);
}

/* Clear button */
clear.onclick = function() {
    h1.textContent = "00:00:00:00";
    milli = 0; seconds = 0; minutes = 0; hours = 0;
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Test Stopwatch</title>
        <link rel="stylesheet" href="assets/css/styles.css">
    </head>
    <body>
        <section>
            <h1>
                <time>00:00:000:00</time>
            </h1>

            <button id="start">START</button>
            <button id="stop">STOP</button>
            <button id="clear">CLEAR</button>
        </section>
        <script src="assets/js/script.js"></script>
    </body>
</html>

标签: javascript

解决方案


timer()对 javascript 文件范围的根有一个调用,因此它会被自动调用。

function timer() {
    t = setTimeout(add, 10);
}
timer(); // This starts it automatically. remove it.

正确的:

function timer() {
    t = setTimeout(add, 10);
}

推荐阅读