每次点击“开始”按钮,定时器加速。反之,如果按下“停止”按钮,它会开始减速并最终停止。有什么方法可以阻止这种情况,只要按下“开始”按钮就可以启动,但不会加速?
function timeKeeper() {
var h1 = $('#headTime')[0],
start = $('#start'),
stop = $('#stop'),
clear = $('#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);
}
/* Start button */
$('#start').on('click', function() {
timer();
});
/* Stop button */
$('#stop').on('click', function() {
clearTimeout(t);
});
/* Clear button */
$('#clear').on('click', function() {
h1.textContent = "00.00.00";
seconds = 0;
minutes = 0;
hours = 0;
});
答案 0 :(得分:0)
您需要在开始新计时器时取消旧计时器。
$('#start').on('click', function() {
clearTimeout(t);
timer();
});