javascript倒计时器暂停恢复
作者:互联网
起初我的倒数计时器没有暂停和恢复功能,计时器运行正常.现在我刚刚添加了该功能,没有问题暂停,但有问题恢复时间.时间不会显示从那里开始,倒计时从那里开始.如何更改我的代码?
$('#pause').click(function(){
// Get current minutes and seconds //
var text = $('#countdown').html();
var min_sec = text.split(":");
pause_minutes = min_sec[0];
pause_seconds = min_sec[1];
// Stop the timer //
clearTimeout(stop_start);
// Hide pause button, show the play button //
$('#pause').hide();
$('#cont').show();
});
// continue button is clicked //
$('#cont').click(function(){
$('#cont').hide();
$('#pause').show();
// Pass in pause_minutes and pause_seconds //
resume_time(pause_minutes, pause_seconds);
});
function resume_time(pause_minutes, pause_seconds){ // e.g: 1 , 30
var start_time = new Date();
end_time.setMinutes(start_time.getMinutes() + pause_minutes);
end_time.setSeconds(start_time.getSeconds() + pause_seconds);
update_timer();
}
function update_timer(){
var current_time = new Date();
var remaining_time = new Date();
remaining_time.setTime(end_time.getTime() - current_time.getTime());
var minutes = remaining_time.getMinutes();
var seconds = remaining_time.getSeconds();
if(seconds < 10){
seconds = '0'+seconds.toString();
}
$("#countdown").text(minutes+":"+seconds);
// call itself every second if //
if(minutes == '0' && seconds == '00'){
$('.big_words').html('Sorry, times up');
$('.overlay').show();
setTimeout(function(){
location.reload();
}, 2000);
exit;
}
stop_start = setTimeout(update_timer,1000);
}
解决方法:
我写了一个小计时器让你进入它;-)
这是一个工作的例子:http://jsfiddle.net/rnQ2W/2/
var CountDown = (function ($) {
// Length ms
var TimeOut = 10000;
// Interval ms
var TimeGap = 1000;
var CurrentTime = ( new Date() ).getTime();
var EndTime = ( new Date() ).getTime() + TimeOut;
var GuiTimer = $('#countdown');
var GuiPause = $('#pause');
var GuiResume = $('#resume').hide();
var Running = true;
var UpdateTimer = function() {
// Run till timeout
if( CurrentTime + TimeGap < EndTime ) {
setTimeout( UpdateTimer, TimeGap );
}
// Countdown if running
if( Running ) {
CurrentTime += TimeGap;
if( CurrentTime >= EndTime ) {
GuiTimer.css('color','red');
}
}
// Update Gui
var Time = new Date();
Time.setTime( EndTime - CurrentTime );
var Minutes = Time.getMinutes();
var Seconds = Time.getSeconds();
GuiTimer.html(
(Minutes < 10 ? '0' : '') + Minutes
+ ':'
+ (Seconds < 10 ? '0' : '') + Seconds );
};
var Pause = function() {
Running = false;
GuiPause.hide();
GuiResume.show();
};
var Resume = function() {
Running = true;
GuiPause.show();
GuiResume.hide();
};
var Start = function( Timeout ) {
TimeOut = Timeout;
CurrentTime = ( new Date() ).getTime();
EndTime = ( new Date() ).getTime() + TimeOut;
UpdateTimer();
};
return {
Pause: Pause,
Resume: Resume,
Start: Start
};
})(jQuery);
jQuery('#pause').on('click',CountDown.Pause);
jQuery('#resume').on('click',CountDown.Resume);
// ms
CountDown.Start(120000);
标签:javascript,countdowntimer,timer 来源: https://codeday.me/bug/20191007/1864831.html