如何在 JavaScript 中设置倒计时器?


我们可以使用 setInterval() 方法在 JavaScript 中设置倒计时器。此方法会以每次调用之间固定的时间延迟不断调用函数或执行代码片段。

setInterval() 方法以描述的间隔以毫秒为单位调用函数。它将继续调用函数直到调用 clearInterval() 或关闭窗口。

语法

以下是此方法的语法 −

setInterval(function, milliseconds);

setInterval 方法接受两个参数函数和毫秒。

  • 函数 − 包含旨在执行特定任务的代码块的函数。

  • 毫秒 − 这是函数执行之间的间隔时间。

此方法将返回一个正整数,表示间隔 ID。

示例

在以下示例中,我们从 2027 年 1 月 1 日 12:12:50 创建一个倒计时器到当前时间。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>countDownTimer</title>
   <style>
      h3 {
         text-align: center;
         margin-top: 0px;
      }
   </style>
</head>
<body>
   <h3 id="time"></h3>
   <script>
      // set the date we are counting down to
      var countDown = new Date("jan 1, 2027 12:12:50").getTime();
     
      //update the count down in every 1 second
      var update = setInterval(function () {
     
         // get the today's date and time
         var now = new Date().getTime();
       
         //find the difference b/w countDown and now
         var diff = countDown - now;
       
         //now we are calculating time in days, hrs, minutes, and seconds.
         var days = Math.floor(diff / (1000 * 60 * 60 * 24));
         var hrs = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
         var minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
         var seconds = Math.floor((diff % (1000 * 60)) / 1000);
       
         //now output the result in an element with id ="time"
         document.getElementById("time").innerHTML =
         days + "-D: " + hrs + "-H: " + minutes + "-M: " + seconds + "-S ";
         if (diff < 0) {
            clearInterval(update);
            document.getElementById("time").innerHTML = "Expired";
         }
      }, 1000);
   </script>
</body>
</html>

更新于:19-12-2022

8K+ 浏览量

启动您的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.