倒计时设置

预计阅读时间: 小于 1 分钟

适用背景

  动态更新倒计时:天、小时、分钟、秒。

倒计时函数:countDown

代码示例
1data() {
2	// vue 定义默认数据
3	return {
4		isStart: false,
5		isEnd: false,
6		d: 0,
7		h: 0,
8		m: 0,
9		s: 0,
10		timer: null,
11		btnInfo: ""
12	};
13},
14
15// 倒计时
16countdown() {
17	// 清除定时器
18	clearTimeout(this.timer);
19	const nowTime = new Date().getTime(),
20		start = "开始时间",
21		end = "结束时间";
22	let startTime = new Date(start).getTime(),
23		endTime = new Date(end).getTime();
24
25	// 时间差
26	let diff = startTime - nowTime;
27	if (diff <= 0) {
28		this.isStart = true;
29		if (endTime - nowTime <= 0) {
30			this.isStart = false;
31			this.isEnd = true;
32		} else {
33			this.timer = setTimeout(this.countdown, 30000);
34		}
35		return;
36	} else {
37		// 动态计算 天、小时、分钟、秒
38		this.d = Math.floor(diff / 36e5 / 24);
39		this.h = Math.floor((diff / 36e5) % 24);
40		this.m = Math.floor((diff / 6e4) % 60);
41		this.s = Math.floor((diff / 1000) % 60);
42
43		// 递归调用
44		this.timer = setTimeout(this.countdown, 1000);
45	}
46}

JavaScript 版

代码示例
1// 活动开始时间
2const start = "2020/03/16 21:31:00";
3
4// 倒计时函数(传参数)
5function countDown(start) {
6	// 清除定时器
7	!!timer && clearTimeout(timer);
8
9	// 获取时间毫秒数
10	let begin = new Date(start).getTime(),
11		now = new Date().getTime();
12
13	// 判断当前时间小于开始时间
14	if (now < begin) {
15		// 计算时间差
16		let cha = begin - now;
17
18		// 获取 天时分秒
19		let day = Math.floor(cha / 36e5 / 24),
20			hour = Math.floor((cha / 36e5) % 24),
21			minute = Math.floor((cha / 6e4) % 60),
22			second = Math.floor((cha / 1000) % 60);
23
24		// 拼接字符串
25		let timeSting = "";
26		!!day && (timeSting += day + "天");
27		!!hour && (timeSting += hour + "时");
28		!!minute && (timeSting += minute + "分");
29		timeSting += second + "秒";
30
31		// 打印字符串
32		console.log(timeSting);
33
34		// 调用封装的倒计时函数
35		timer = setTimeout(() => {
36			countDown(activeStart);
37		}, 1000);
38	}
39}
40// 调用计时器
41countDown(start);

延时定定时器「后台返回时间差」

代码示例
1countDown(time) {
2	if (time == 0) {
3		this.isLive = true;
4		this.timer && clearTimeout(this.timer);
5		this.timeString = "";
6		return;
7	}
8	const addZero = n => (n < 10 ? "0" + n : n);
9	const checkTime = (n, type) => (n ? n + type : "");
10	let diff = time - 1;
11	let d = Math.floor(diff / 3600 / 24),
12		h = Math.floor((diff / 3600) % 24),
13		m = Math.floor((diff / 60) % 60),
14		s = Math.floor(diff % 60);
15	d = addZero(d);
16	h = addZero(h);
17	m = addZero(m);
18	s = addZero(s);
19	d = d === "00" ? 0 : d;
20	if (h === "00") h = d === 0 ? 0 : h;
21	if (m === "00") m = d === 0 && h === 0 ? 0 : m;
22	let _d = checkTime(d, "天"),
23		_h = checkTime(h, "时"),
24		_m = checkTime(m, "分");
25	this.timeString = `距开始${_d}${_h}${_m}${s + "秒"}`;
26	// 递归调用
27	this.timer = setTimeout(() => {
28		this.countDown(diff);
29	}, 1000);
30}
31// 调用函数:时间差 number 类型数据
32this.countDown('时间差')