Javascript秒表自动启动

时间:2015-04-30 12:47:00

标签: javascript html

我的页面上有一个Javascript / HTML秒表,但只要页面加载,它就会自动启动。我是Java-illiterate,有人可以调整代码,以便它只在按下“开始”按钮时启动吗?

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

function add() {
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);

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


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

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

/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}

1 个答案:

答案 0 :(得分:2)

您在函数定义后调用timer() ..删除该行:

function timer() {
t = setTimeout(add, 1000);
}
// timer(); // comment this line