JS 实现倒计时功能

JS 定时器

setInterval

setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。
由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。

/*
	1.uniapp中使用定时器,实现倒计时功能
	2.需要在页面销毁的时候,清除定时器
	3.每次生成定时器前,必须判断,该定时器是否存在,如果存在,就return(不可重复生成)
*/
<template>
	<view>剩余时间:{{str}}</view>
</template>

<script>
	import moment from "dayjs";
	export default {
		props: {
			date: {
				type: String,	
				default () {
					return "";
				},
			},
		},
		data() {
			return {
				timer: null,
				str: ""
			}
		},
		created() {
			let {
				date,
			} = this;
			let str = ''
			if (!this.timer) {
				this.timer = setInterval(() => {
					let day = moment(date).diff(moment(), 'days');
					let hour = moment(date).diff(moment(), 'hours') % 24;
					let minute = moment(date).diff(moment(), 'minutes') % 60;
					let second = moment(date).diff(moment(), 'seconds') % 60;
					day = day < 10 ? `0${day}` : day;
					hour = hour < 10 ? `0${hour}` : hour;
					minute = minute < 10 ? `0${minute}` : minute;
					second = second < 10 ? `0${second}` : second;
					if (day > 0) {
						str = `${day}${hour}${minute}${second}秒`;
					} else if (hour > 0) {
						str = `${hour}${minute}${second}秒`;
					} else if (minute > 0) {
						str = `${minute}${second}秒`;
					} else if (second > 0) {
						str = `${second}秒`;
					} else {
						str = '--'
					}
					this.str = str;
				}, 1000)
			}
		},
		destroyed() {
			if (this.timer) {
				clearInterval(this.timer)
				this.timer = null;
			}
		}
	};
</script>

<style scoped></style>

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值