示例: 创建倒数计时器
// 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 纪元) 午夜到指定日期(此处为当前日期)的毫秒数。
以下代码以毫秒为单位给出第二天的时间。
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();