Search code examples
javascripthtmltimer

Countdown timer stops ticking when the phone screen is locked


I wrote a code - a timer that measures the number of seconds entered. While the timer counts down the seconds when I lock the phone screen, after unlocking the screen after a long time, the timer stopped a few seconds after locking the screen. Is there any way to fix this?

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>

Solution

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