我得到了我不久前为自己写的这个计时器。昨天我实现了暂停功能,但是当我暂停它时,记录暂停时间并尝试再次将其传递给新计时器 - 它比我暂停时更早开始。我整天都在挖掘,并且确定问题出在何处。
请帮忙。
P.S。忽略/1000
,我需要unix时间戳用于不同目的=)
var timerId;
function startTimer(started) {
var localTime = new Date()/1000;
return setInterval(function() {
var totalSeconds = ((new Date()/1000) - started);
var hours = Math.floor(totalSeconds / 3600);
totalSeconds = totalSeconds % 3600;
var minutes = Math.floor(totalSeconds / 60);
totalSeconds = totalSeconds % 60;
var seconds = Math.floor(totalSeconds);
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
var timeString = hours + ":" + minutes + ":" + seconds;
$('.timer .digits').text(timeString);
}, 1000);
}
$('.start button').click(function() {
timerId = startTimer(new Date()/1000);
$('.start').hide().siblings('.pause').show();
});
$('.pause button').click(function() {
var pausedTime = new Date()/1000;
clearInterval(timerId);
$('.timer').data('pausedTime', pausedTime);
$('.pause').hide().siblings('.resume').show();
});
$('.resume button').click(function() {
var pausedTime = $('.timer').data('pausedTime');
timerId = startTimer(pausedTime);
$('.resume').hide().siblings('.pause').show();
});
&#13;
.pause, .resume {
display: none
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='timer'>
<div class='digits'>00:00:00</div>
<div class='start'><button>Start</button></div>
<div class='pause'><button>Pause</button></div>
<div class='resume'><button>Resume</button></div>
</div>
&#13;
答案 0 :(得分:0)
希望你能找到这样的东西。由于这是一个计时器,您不需要特定的时间,只需保留已用时间并在恢复时获取。
var timerId;
function startTimer() {
var elapsed = ($('.timer').data('pausedTime') | 0) || 0;
return setInterval(function() {
var totalSeconds = elapsed;
var hours = Math.floor(totalSeconds / 3600);
totalSeconds = totalSeconds % 3600;
var minutes = Math.floor(totalSeconds / 60);
totalSeconds = totalSeconds % 60;
var seconds = Math.floor(totalSeconds);
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
var timeString = hours + ":" + minutes + ":" + seconds;
$('.timer .digits').text(timeString);
$('.timer').data('pausedTime', ++elapsed);
}, 1000);
}
$('.start button').click(function() {
timerId = startTimer();
$('.start').hide().siblings('.pause').show();
});
$('.pause button').click(function() {
clearInterval(timerId);
$('.pause').hide().siblings('.resume').show();
});
$('.resume button').click(function() {
timerId = startTimer();
$('.resume').hide().siblings('.pause').show();
});
.pause, .resume {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='timer'>
<div class='digits'>00:00:00</div>
<div class='start'><button>Start</button></div>
<div class='pause'><button>Pause</button></div>
<div class='resume'><button>Resume</button></div>
</div>