countDown 倒计时(天、时、分、秒)


适用背景:
动态更新倒计时:天、小时、分钟、秒。

倒计时函数:countDown

(vue 版)

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);


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM