如何在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 宝宝100日简短祝福语
13 创业大吉祝福语简短
14 友谊诗歌祝福语大全简短
15 七姐妹新春祝福语简短
16 给医生简短新年祝福语
17 老同学十一祝福语简短
18 兔年祝福语简短100字