我现在对我所拥有的东西做了以下小提琴..
https://jsfiddle.net/r5yj99bs/1/
当我进入某个页面时,我尝试启动,但允许该选项保留暂停/恢复选项。然后,无论如何都要显示剩余时间为5分钟'而不是' 300秒'然后倒数,而不是仅仅几秒钟。
<button class="start-pause">Start</button>
<h2 class="time-left"></h2>
var times = [];
var counter_interval;
var $time_left = $('.time-left');
var $button = $('.start-pause');
// timer length in seconds
var timer_length = 300;
$('body').on('click', '.start-pause', function() {
// are we starting or stopping?
var starting = times.length % 2 == 0;
times.push(Date.now());
if (starting) {
$button.html('Pause');
counter_interval = setInterval(function() {
var time_left = Math.floor(timer_length - sum_elapsed());
if (time_left < 1) {
clearInterval(counter_interval);
return finished();
}
$time_left.html(time_left);
}, 100);
} else {
$button.html('Resume');
clearInterval(counter_interval);
}
});
var sum_elapsed = function() {
sum = 0;
for (var i=0; i<times.length; i++) {
if (i % 2 == 1) {
sum += (times[i] - times[i-1]);
}
if (i == (times.length - 1)) {
sum += (Date.now() - times[i]);
}
}
// convert milliseconds to seconds
return sum / 1000;
};
var finished = function() {
$button.attr('disabled','disabled').html('Finished');
$time_left.html("Time's Up");
};
答案 0 :(得分:0)
有一个很好的时间模块叫做时刻。您可以通过npm或者来自moments.com
获取它这可以格式化人类可读字符串的相对时间。
如果您想自己动手,请使用秒模数60来获取分钟数。使用模数,您可以提取有关小时数的所有信息,等等。
答案 1 :(得分:0)
您可以更改以下行:
$time_left.html(time_left);
于:
$time_left.html(secToMinTxt(time_left));
并添加以下功能:
function pad(num) {
var str = "" + num;
var pad = "00";
return pad.substring(0, pad.length - str.length) + str;
}
function secToMinTxt(seconds) {
var min = Math.floor(seconds / 60);
var sec = seconds % 60;
return pad(min) + ":" + pad(sec);
}
JSFiddle参考:https://jsfiddle.net/r5yj99bs/2/
答案 2 :(得分:0)
如果正确解释问题,请尝试将Math.round
与参数现有time_left
变量除以60
var time_left = Math.round(Math.floor(timer_length - sum_elapsed()) / 60);
jsfiddle https://jsfiddle.net/r5yj99bs/3/