我写了一个代码-一个计时器,用于测量输入的秒数。虽然在我锁定手机屏幕时计时器会倒数秒,但长时间锁定屏幕后,计时器会在锁定屏幕后停止几秒钟。有什么办法可以解决这个问题?
document.getElementById('btn').addEventListener('click',function(){
var workSeconds = parseInt(document.getElementById('work-seconds').value);
var workSecondsCount = workSeconds;
var worktimer = setInterval(workSecCount,1000);
function workSecCount(){
workSecondsCount--;
workSecondsCount < 10 ? document.getElementById('workSecs').textContent = "0" + workSecondsCount : document.getElementById('workSecs').textContent = workSecondsCount;
if(workSecondsCount == 0){
document.getElementById('workSecs').textContent = "DONE";
workSecondsCount = workSeconds;
clearInterval(worktimer);
}
};
});
<input type="number" id="work-seconds" placeholder="seconds" min="0">
<button id="btn">START</button>
<p>Work Timer : <span id="workSecs"></span></p>
答案 0 :(得分:2)
您无需依靠workSecondsCount
,而只需依靠当前时间,就可以补偿时间间隔。
var worktimer = 0;
document.getElementById('btn').addEventListener('click',function(){
if (!worktimer) clearInterval(worktimer);
var workSeconds = parseInt(document.getElementById('work-seconds').value);
var workSecondsCount = new Date().getTime() + workSeconds * 1000;
function workSecCount(){
const secondsCount = Math.ceil((workSecondsCount - new Date().getTime()) / 1000);
secondsCount < 10 ? document.getElementById('workSecs').textContent = "0" + secondsCount : document.getElementById('workSecs').textContent = secondsCount;
if(secondsCount <= 0){
document.getElementById('workSecs').textContent = "DONE";
if (worktimer) {
clearInterval(worktimer);
worktimer = 0;
}
}
};
workSecCount();
worktimer = setInterval(workSecCount,1000);
});