Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript count down, add hours & minutes

So, I have the below (seconds countdown) in good order. But! I am trying to add hours & minutes as apart of the count down as well. Ideally keeping the same structure, and just using pure JS. I would like the output to be:

There is X hours, X minutes, and X seconds remaining on this Sale!

var count=30;

    var counter=setInterval(timer, 1000); //1000 will  run it every 1 second

    function timer()
    {
      count=count-1;
      if (count <= 0)
      {
         clearInterval(counter);
         return;
      }

     document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
    }

If the solution has to be a rewrite with jQuery or another library; that's fine. Just not preferable. Cheers and Salutations for any help.

like image 524
fred randall Avatar asked Nov 30 '22 12:11

fred randall


2 Answers

Something like this:

var count = 30;
var counter = setInterval(timer, 1000); //1000 will  run it every 1 second

function timer() {
    count = count - 1;
    if (count == -1) {
        clearInterval(counter);
        return;
    }

    var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    document.getElementById("timer").innerHTML = hours + "hours " + minutes + "minutes and" + seconds + " seconds left on this Sale!"; // watch for spelling
}
like image 157
putvande Avatar answered Dec 10 '22 15:12

putvande


var totalSeconds = 3723; // lets say we have 3723 seconds on the countdown
                         // that's 1 hour, 2 minutes and 3 seconds.

var hours   = Math.floor(totalSeconds / 3600 );
var minutes = Math.floor(totalSeconds % 3600 / 60);
var seconds = totalSeconds % 60;

var result = [hours, minutes, seconds].join(':');
console.log(result);
// 1:2:3
  • hours is seconds divided by the number of seconds in hour (3600) rounded down
  • minutes is the remainder of the above division, divided by the number of seconds in a minute (60), rounded down.
  • seconds is the remainder of total seconds divided by seconds in a minute.

Each calculation after hour has to use a modulus calculation to get the remainder, because you don't care about total time at that step, just progress to the next tick.

like image 22
Alex Wayne Avatar answered Dec 10 '22 16:12

Alex Wayne