David Jawphan David Jawphan - 4 months ago 8
Javascript Question

How to make countdown function with hourly?

I tried to make countdown function , It is work unless hour time ! But I want to make 2 hours countdown time , I can't figure more ?

<div id="time"></div>
<script type="text/javascript">
var hour = 2 ;
var min = 30;
var countdown = hour * min * 60 * 1000;
//var countdown = hour * 3600 * min * 60 * 1000; also not working
var timeload = setInterval(function () {
countdown -= 1000;
var hr = Math.floor(countdown/(60 * 60 * 1000));
var min = Math.floor(countdown / (60 * 1000));
var sec = Math.floor((countdown - (min * 60 * 1000)) / 1000);

if (countdown <= 0) {
alert("Timeout !");
clearInterval(timeload);
}
else {
$("#time").html("<font color='red'>Allowed Time </font>" + hr + " : " + min + " : " + sec);
}
}, 1000);
</script>


Actual Started Time
Allowed Time 0 : 59 : 59

Expected Start Time Allowed Time 2 : 29 : 59

Answer

you can try this solution, you have an error on calculation time (hr, min, sec) it should modulus to maximum each value and also you wrong when convert hour and min to millisecond

var hour = 2 ;
var min = 30;
var countdown = (hour * 60 * 60 * 1000) + (min * 60 * 1000);
var timeload = setInterval(function () {
  countdown -= 1000;
  var hr   = Math.floor( (countdown / (60 * 60 * 1000)) % 24 );
  var min = Math.floor( (countdown / (60 * 1000)) % 60 );
  var sec = Math.floor( (countdown / 1000) % 60 );  

  if (countdown <= 0) {
    alert("Timeout !");
    clearInterval(timeload);           
  }
  else {            
    $("#time").html("<font color='red'>Allowed Time </font>" + hr + " : " + min + " : " + sec);
  }
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>