如何在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 新年送老师简短祝福语