【发布时间】:2017-04-07 23:38:39
【问题描述】:
我一直在研究 Javascript 番茄钟。我可以设置会话时间和休息时间,它倒计时没有任何麻烦。但由于某种原因,我无法暂停并恢复工作。当计时器启动时,我捕获 Date.now(),当我暂停它时,我捕获当前的 Date.now()。我找到了差异并从持续时间中减去,希望在暂停的时间恢复,但它仍然会继续减去额外的秒数。我的代码(来自codepen)在下面
$(document).ready(function() {
var total;
var i;
var x;
var y;
var display;
var minutes;
var seconds;
var duration;
var sessionInterval;
var freeze;
var timePast;
var t;
var start;
var clock;
function timer(end) {
total = Date.parse(end) - Date.parse(new Date());
minutes = Math.floor((total / 1000 / 60) % 60);
seconds = Math.floor((total / 1000) % 60);
return {
'total': total,
'minutes': minutes,
'seconds': seconds
};
}
function beginTimer() {
start = Date.now();
clearInterval(sessionInterval);
clock = document.getElementById('display2');
start = Date.now();
sessionInterval = setInterval(function() {
t = timer(duration);
clock.innerHTML = 'minutes:' + t.minutes + '<br>' + 'seconds:' + t.seconds + '<br>';
if (t.total <= 0) {
clearInterval(sessionInterval);
if (i === 0) {
session();
} else if (i === 1) {
breakTime();
}
}
}, 1000);
}
function session() {
duration = new Date(Date.parse(new Date()) + (x * 60 * 1000));
beginTimer();
i = 1;
}
function breakTime() {
duration = new Date(Date.parse(new Date()) + (y * 60 * 1000));
beginTimer();
i = 0;
}
$(".sendInput").click(function() {
if (x == null) {
x = 25;
} else {
x = parseInt(document.getElementById("workTime").value, 10);
}
if (y == null) {
y = 5;
} else {
y = parseInt(document.getElementById("breakMin").value, 10);
}
session();
});
$(".sendPause").click(function() {
freeze = Date.now();
timePast = freeze - start;
clearInterval(sessionInterval);
});
$(".sendResume").click(function() {
if (i === 1) {
duration = new Date(((Date.parse(new Date())) + (x * 60 * 1000)) - timePast);
}
if (i === 0) {
duration = new Date(((Date.parse(new Date())) + (y * 60 * 1000)) + timePast);
}
beginTimer();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="break: 5 minutes" id="breakMin">
<input type ="text" placeholder="session: 25 minutes" id="workTime">
<input type="button" value="Start" class="sendInput">
<input type="button" value="Pause" class="sendPause">
<input type="button" value="Resume" class="sendResume">
<div id="display2">
</div>
【问题讨论】:
-
Date.parse(new Date())没有意义,使用Date.now()。 -
@RobG 这可能是问题所在:
Date.now() - Date.now()的计算结果如预期的那样为零。但是Date.now() - Date.parse(new Date())在 Windows 下的 Firefox 中的计算时间似乎在 5 到 800 毫秒之间。就好像new Date()调用返回“一段时间后”的操作系统,或者Firefox 正在使用new Date()进行多任务处理。 -
这是
new Date()创建一个新的Date对象,然后Date.parse将其转换为字符串,将其解析回日期,然后返回时间值之间的滞后。
标签: javascript timer clock