Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript countdown timer for hour, minutes and seconds when a start button click

I want to create countdown timer for hour,minute and second when a button click. This is my code so far.

HTMLcode

<div class="colomn" style="margin-right: 20px">
   <button class="start" onclick="clock();">Start</button>
</div>

javascript function

<script>
 var myTimer;
 function clock() {
        myTimer = setInterval(myClock, 1000);
        var c = 5;

        function myClock() {
            document.getElementById("demo").innerHTML = --c;
               if (c == 0) {
                   clearInterval(myTimer);
        }
      }
    }
  </script>

This is simple and not showing separate hour,min and sec. How can I apply this for count hour,min and sec. Please help me.

like image 424
Chathuri Fernando Avatar asked Dec 18 '25 06:12

Chathuri Fernando


1 Answers

Working Code:

<!DOCTYPE HTML>
<html>
<body>

<p id="demo"></p>
<button onclick="countdownTimeStart()">Start Timer</button>

<script>
// Set the date we're counting down to

function countdownTimeStart(){

var countDownDate = new Date("Sep 25, 2025 15:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();
    
    // Find the distance between now an the count down date
    var distance = countDownDate - now;
    
    // Time calculations for days, hours, minutes and seconds
    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);
    
    // Output the result in an element with id="demo"
    document.getElementById("demo").innerHTML = hours + "h "
    + minutes + "m " + seconds + "s ";
    
    // If the count down is over, write some text 
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
}, 1000);
}
</script>

</body>
</html>