JavaScript 程序:创建倒计时器

要理解此示例,您应了解以下 JavaScript 编程 主题


示例:创建倒计时器

// program to create a countdown timer

// time to countdown from (in milliseconds)
let countDownDate = new Date().getTime() + 24 * 60 * 60 * 1000;

// countdown timer
let x = setInterval(function() {

    // get today's date and time in milliseconds
    let now = new Date().getTime();

    // find the interval between now and the countdown time
    let timeLeft = countDownDate - now;

    // time calculations for days, hours, minutes and seconds
    const days = Math.floor( timeLeft/(1000*60*60*24) );
    const hours = Math.floor( (timeLeft/(1000*60*60)) % 24 );
    const minutes = Math.floor( (timeLeft/1000/60) % 60 );
    const seconds = Math.floor( (timeLeft/1000) % 60 );

    // display the result in the element with id="demo"
    console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");

    // clearing countdown when complete
    if (timeLeft < 0) {
        clearInterval(x);
        console.log('CountDown Finished');
    }
    }, 2000);

输出

0d 23h 59m 57s 
0d 23h 59m 55s 
0d 23h 59m 53s 
0d 23h 59m 51s 
...

在上面的程序中,使用setInterval()方法创建了一个计时器。

setInterval()方法在给定的时间间隔(此处为2000毫秒)执行。

new Date()给出了当前日期和时间。例如,

let d1 = new Date();
console.log(time); // Fri Aug 28 2020 09:19:40 GMT+0545 (+0545)

getTime()方法返回从1970年1月1日午夜(ECMAScript epoch)到指定日期(此处为当前日期)的毫秒数。

以下代码给出下一天的毫秒时间。

new Date().getTime() + 24 * 60 * 60 * 1000;

现在,我们可以使用以下公式计算剩余时间

let timeLeft = countDownDate - now;

剩余的日期数使用以下公式计算

  • 时间间隔除以1000以确定秒数,即timeLeft / 1000
  • 时间间隔然后除以60 * 60 * 24以确定剩余的天数。
  • Math.floor()函数用于将数字四舍五入为整数。

小时、分钟和秒也使用了类似的方法。


注意:您还可以通过传递特定日期来使用自定义的倒计时开始时间。

例如,

let countDownDate = new Date("Aug 5, 2025 14:22:36").getTime();

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战