且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当手机屏幕锁定时,倒数计时器停止滴答

更新时间:2023-02-26 21:48:11

你需要依靠当前时间而不是workSecondsCount,然后你可以弥补时间差距.

instead of workSecondsCount you need to rely on current time, then you can compensate time gaps.

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);
});