#倒计时
#适用背景
动态更新倒计时:天、小时、分钟、秒。
#倒计时函数:countDown
代码示例
data() {
// vue 定义默认数据
return {
isStart: false,
isEnd: false,
d: 0,
h: 0,
m: 0,
s: 0,
timer: null,
btnInfo: ""
};
},
// 倒计时
countdown() {
// 清除定时器
clearTimeout(this.timer);
const nowTime = new Date().getTime(),
start = "开始时间",
end = "结束时间";
let startTime = new Date(start).getTime(),
endTime = new Date(end).getTime();
// 时间差
let diff = startTime - nowTime;
if (diff <= 0) {
this.isStart = true;
if (endTime - nowTime <= 0) {
this.isStart = false;
this.isEnd = true;
} else {
this.timer = setTimeout(this.countdown, 30000);
}
return;
} else {
// 动态计算 天、小时、分钟、秒
this.d = Math.floor(diff / 36e5 / 24);
this.h = Math.floor((diff / 36e5) % 24);
this.m = Math.floor((diff / 6e4) % 60);
this.s = Math.floor((diff / 1000) % 60);
// 递归调用
this.timer = setTimeout(this.countdown, 1000);
}
}#JavaScript 版
代码示例
// 活动开始时间
const start = "2020/03/16 21:31:00";
// 倒计时函数(传参数)
function countDown(start) {
// 清除定时器
!!timer && clearTimeout(timer);
// 获取时间毫秒数
let begin = new Date(start).getTime(),
now = new Date().getTime();
// 判断当前时间小于开始时间
if (now < begin) {
// 计算时间差
let cha = begin - now;
// 获取 天时分秒
let day = Math.floor(cha / 36e5 / 24),
hour = Math.floor((cha / 36e5) % 24),
minute = Math.floor((cha / 6e4) % 60),
second = Math.floor((cha / 1000) % 60);
// 拼接字符串
let timeSting = "";
!!day && (timeSting += day + "天");
!!hour && (timeSting += hour + "时");
!!minute && (timeSting += minute + "分");
timeSting += second + "秒";
// 打印字符串
console.log(timeSting);
// 调用封装的倒计时函数
timer = setTimeout(() => {
countDown(activeStart);
}, 1000);
}
}
// 调用计时器
countDown(start);#延时定定时器「后台返回时间差」
代码示例
countDown(time) {
if (time == 0) {
this.isLive = true;
this.timer && clearTimeout(this.timer);
this.timeString = "";
return;
}
const addZero = n => (n < 10 ? "0" + n : n);
const checkTime = (n, type) => (n ? n + type : "");
let diff = time - 1;
let d = Math.floor(diff / 3600 / 24),
h = Math.floor((diff / 3600) % 24),
m = Math.floor((diff / 60) % 60),
s = Math.floor(diff % 60);
d = addZero(d);
h = addZero(h);
m = addZero(m);
s = addZero(s);
d = d === "00" ? 0 : d;
if (h === "00") h = d === 0 ? 0 : h;
if (m === "00") m = d === 0 && h === 0 ? 0 : m;
let _d = checkTime(d, "天"),
_h = checkTime(h, "时"),
_m = checkTime(m, "分");
this.timeString = `距开始${_d}${_h}${_m}${s + "秒"}`;
// 递归调用
this.timer = setTimeout(() => {
this.countDown(diff);
}, 1000);
}
// 调用函数:时间差 number 类型数据
this.countDown('时间差')