Search code examples
javascriptcountdownclock

Javascript Clock goes negative


http://jsfiddle.net/8Ab78/448/

I attempted to fix it but failed.

function ShowTime() {
  var now = new Date();
  var tomorrow = new Date();
  tomorrow.setDate(today.getDate() + 1);
  var hrs = 17 - now.getHours();
  var mins = 30 - now.getMinutes();
  var secs = 60 - now.getSeconds();
  if (hrs < 0) {
    var hrs = 17 - tomorrow.getHours();
    var mins = 30 - tomorrow.getMinutes();
    var secs = 60 - tomorrow.getSeconds();
  }
  timeLeft = "" + hrs + ' hours ' + mins + ' minutes ' + secs + ' seconds';
  $("#countdown").html(timeLeft);
}

ShowTime();
var countdown = setInterval(ShowTime, 1000);
<div id="countdown"></div>


Solution

  • Your arithmetic is broken.

    Each time the clock ticks, a new Date is generated. If it's say 18:00 then then:

    var hrs = 17 - now.getHours();
    

    will go negative, so you'll do:

    var hrs = 17 - tomorrow.getHours();
    

    but that will produce -1. What you want to do is create a date for the end time, then subtract the current Date from that and resolve the result (milliseconds) to hours, minutes and seconds.

    I don't know what the minutes and seconds adjustments are for, they don't make sense to me. The following makes minor adjustments to your code:

    function ShowTime() {
      var now = new Date();
      var end = new Date(+now);
      var endHour = 17;
      end.setHours(endHour,0,0,0);
    
      // If past end, set to tomorrow
      if (now >= end) {
        end.setDate(end.getDate() + 1);
      }
    
      console.log('Counting down to ' + end.toString());
      
      // Get difference and divide into hr, min, sec
      var diff = end - now;
      var hrs = diff / 3.6e6 | 0;
      var mins = (diff % 3.6e6)/ 6e4 | 0;
      var secs = (diff % 6e4) / 1000 | 0;
      
      // Format and write to document
      timeLeft = "" + hrs + ' hours ' + mins + ' minutes ' + secs + ' seconds';
      document.getElementById('countdown').innerHTML = timeLeft;
    }
    
    ShowTime();
    var countdown = setInterval(ShowTime, 1000);
    <div id="countdown"></div>

    If you're trying to get a countdown to say 17:30, then introduce an endMin variable like:

      var endHour = 17;
      var endMin  = 30;
      end.setHours(endHour, endMin, 0, 0);
    
      // If past end hour, set to tomorrow
      if (now > end) {