如何在JavaScript中设置倒数计时器?
您可以使用setInterval方法在Javascript中创建倒数计时器。该setInterval()方法重复调用函数或执行代码段,每次调用之间有固定的时间延迟。
要创建倒计时,我们需要检查当前时间与最终时间之间的时差,并继续更新倒计时。例如,
示例
let countDownDate = new Date("Jul 21, 2020 00:00:00").getTime();
let x = setInterval(() => {
let now = new Date().getTime();
let distance = countDownDate - now;
//天,小时,分钟和秒的时间计算
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s");
//如果倒计时完成,请写一些文字
if (distance < 0) {
clearInterval(x);
console.log("completed")
}
}, 1000);输出结果
这将给出输出-
310d 0h 6m 46s 310d 0h 6m 45s 310d 0h 6m 44s 310d 0h 6m 43s 310d 0h 6m 42s 310d 0h 6m 41s 310d 0h 6m 40s 310d 0h 6m 39s 310d 0h 6m 38s 310d 0h 6m 37s 310d 0h 6m 36s 310d 0h 6m 35s 310d 0h 6m 34s 310d 0h 6m 33s
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短