我的问题是计时器没有正确暂停。当我点击暂停时,它看起来已经停止但实际上它继续循环,当我点击开始时,它不会从我暂停的地方继续,而是从它到达的位置继续。
<div class="stopwatch">
<span>00:00:00,000</span><br />
<div class="btn start">play</div>
<div class="btn pause">pause</div>
<div class="btn reset">reset</div>
</div>
$(function (){
var reload = 1000/60;
var timer = null;
var startTime = 0;
var btn = $('.stopwatch a');
var count = $('.stopwatch span');
var pause = false;
$('.pause').click(function (){
pause = true;
});
$('.start').click(function (){
pause = false;
});
$('.reset').click(function (){
return ( (count.text('00:00:00,000')) && (timer = 0) );
});
function zero(num, length) {
if ( typeof(length) == 'undefined' ) length = 2;
while ( num.toString().length < length ) {
num = '0' + num;
}
return num;
}
function zero_format(time){
return zero(time.getUTCHours()) + ':' + zero(time.getMinutes()) + ':' + zero(time.getSeconds()) + ',' + zero(time.getMilliseconds());
}
$('.start').click( function (){
if ( !timer ){
startTime = new Date();
timer = setInterval( function (){
if ( pause ){
return;
}
var currentTime = new Date(new Date() - startTime);
count.text(zero_format(currentTime));
}, reload);
}
return false;
});
});