简体   繁体   中英

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.

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>

Simple Answer would be as follows, html part,

<button onclick="clockStart()">Start</button>

<p id="demo"></p>

JS part,

function clockStart() {
          setInterval(function() {
                     date = new Date()
                     let hour = date.getHours();
                     let minutes = date.getMinutes();
                     let seconds = date.getSeconds();
                     document.getElementById("demo").innerHTML = hour + ":"+ minutes + ":" + seconds;
        }, 1000);
    }

You need a counter for seconds. During each 1 second interval, decrement this counter, and do the necessary calculations.

var myTimer;
function clock() {
    myTimer = setInterval(myClock, 1000);
    var c = 3610; //Initially set to 1 hour


    function myClock() {
        --c
        var seconds = c % 60; // Seconds that cannot be written in minutes
        var secondsInMinutes = (c - seconds) / 60; // Gives the seconds that COULD be given in minutes
        var minutes = secondsInMinutes % 60; // Minutes that cannot be written in hours
        var hours = (secondsInMinutes - minutes) / 60;
        // Now in hours, minutes and seconds, you have the time you need.
        console.clear();
        console.log(hours + ":" + minutes + ":" + seconds)
        if (c == 0) {
            clearInterval(myTimer);
        }
    }
}

clock();

Put it in a fiddle as well. See if it works..

EDIT : Updated the erroneous code. Thanks to @JDrake for pointing the fact out...

Here is a very primordial clock for you:

 function clock(t){
    if(clock._stop){return};
    var d = new Date(Date.now());
    console.log(d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+":"+d.getMilliseconds())
    window.requestAnimationFrame(clock);
}
    clock._stop = false;
    clock();

check your console. To stop the clock do clock._stop = true ; To start it, set it back to false and call like clock() . You can wrap the logic inside an other object with getters/setters or whatever you prefer.

FIDDLE

You can try this;

    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <!-- This will start a timer for 5 hours 6 minutes and 7 seconds -->
    <button onclick="countdown(5,6,7)"> Start </button>
    <div><h3 id="timer"></h3></div>
    <script>
    function countdown(hr,mm,ss)
    {
        var interval = setInterval(function(){

            if(hr == 0 && mm == 0 && ss == 0)clearInterval(interval);
            ss--;
            if(ss == 0)
            {
                ss = 59;
                mm--;
                if(mm == 0)
                {
                    mm = 59;
                    hr--;
                }
            }

            if(hr.toString().length < 2) hr = "0"+hr;
            if(mm.toString().length < 2) mm = "0"+mm;
            if(ss.toString().length < 2) ss = "0"+ss;
            $("#timer").html(hr+" : "+mm+" : "+ss);

        },1000)
    }
    </script>

You can convert the value in seconds to one in hours, minutes, and seconds:

var secs  = Math.floor(c % 60);
var mins  = Math.floor((c/60) % 60);
var hours = Math.floor((c/(60*60)));

This will yield you the amount of seconds left over when removing the minutes (using the modulus operator) and then repeats this for the minutes and hours. You can also easily extend this to include days or weeks:

var hours = Math.floor((c/(60*60)) % 24);
var days = Math.floor((c/(60*60*24) % 7);
var weeks = Math.floor((c/60*60*24*7));

Your code does suffer from one downside: if for some reason the calls become slightly further apart, this might increasingly build a delay. You might instead want to use the lines:

endTime = Date.parse(new Date()) + delay;
timeLeft = endTime - Date.parse(new Date());

 var seconds_inputs = document.getElementsByClassName('deal_left_seconds'); var total_timers = seconds_inputs.length; for ( var i = 0; i < total_timers; i++){ var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_'; var seconds_prod_id = seconds_inputs[i].getAttribute('data-value'); var cal_seconds = seconds_inputs[i].getAttribute('value'); eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';'); eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';'); } function timer() { for ( var i = 0; i < total_timers; i++) { var seconds_prod_id = seconds_inputs[i].getAttribute('data-value'); var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60); var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400)); var hours = Math.floor(hoursLeft / 3600); var minutesLeft = Math.floor((hoursLeft) - (hours * 3600)); var minutes = Math.floor(minutesLeft / 60); var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60; function pad(n) { return (n < 10 ? "0" + n : n); } document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days); document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours); document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes); document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds); if (eval('seconds_'+ seconds_prod_id) == 0) { clearInterval(countdownTimer); document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0); } else { var value = eval('seconds_'+seconds_prod_id); value--; eval('seconds_' + seconds_prod_id + '= ' + value + ';'); } } } var countdownTimer = setInterval('timer()', 1000);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="hidden" class="deal_left_seconds" data-value="1" value="8888888"> <div class="box-wrapper"> <div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div> </div> <div class="box-wrapper"> <div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div> </div> <div class="box-wrapper"> <div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div> </div> <div class="box-wrapper hidden-md"> <div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div> </div>

 <!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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM