首页 > 解决方案 > 单击开始按钮时的 JavaScript 倒数计时器,用于小时、分钟和秒

问题描述

我想在单击按钮时为小时、分钟和秒创建倒数计时器。到目前为止,这是我的代码。

HTML代码

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

javascript函数

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

这很简单,不显示单独的小时、分钟和秒。我如何将其应用于计数小时、分钟和秒。请帮我。

标签: javascripthtml

解决方案


工作代码:

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


推荐阅读