Javascript clock and countdown using setInterval for second count is not working correctly

Viewed 86

I'm working with javascript clock and countdown using setInterval.

Below is the working demo and as You can see this working good. But I wonder why the second count from clock and countdown is not correctly. Example if clock second is 40 then countdown second should be 20.

Any idea how to solve this?

function addZero(x)
{
  if(x < 10)
  {
    return x = '0' + x;
  }
  else
  {
    return x;
  }
}

function clockUpdate()
{
  var date = new Date();

  var h = addZero(date.getHours());
  var m = addZero(date.getMinutes());
  var s = addZero(date.getSeconds());

  $('#clock').text(h + ':' + m + ':' + s)
}
clockUpdate();
setInterval(clockUpdate, 1000);

var upComingPrayDate = new Date("Mar 20, 2021 15:30:00").getTime();

var x = setInterval(function()
{
  var now = new Date().getTime();

  var distance = upComingPrayDate - now;

  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
  
  $("#upComingPrayTime").html(addZero(hours) + ":"+ addZero(minutes) + ":" + addZero(seconds));

  if(distance < 0)
  {
    clearInterval(x);
    alert("Done");
  }
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Clock
<div id="clock"></div>
<br>
Countdown
<div id="upComingPrayTime"></div>

1 Answers

The countdown seems to be off by 1 second. That's because you are calculating the floor value of the remaining seconds. This can be overcome by calculating the ceiling value.

Change this line

var seconds = Math.floor((distance % (1000 * 60)) / 1000);

to

var seconds = Math.ceil((distance % (1000 * 60)) / 1000);
Related