uniapp - 倒计时组件-优化循环时间倒计时

使用定时器的规避方法
为了避免定时器误差导致倒计时计算错误,可以采用一些规避方法,比如将倒计时被中断时的剩余时间记录下来,重新开启定时器时再将这个剩余时间加到新的计算中。同时,为了避免定时器延迟,可以在每次执行回调函数时,记录当前时间戳,再计算与上一次执行回调函数的时间差,来调整倒计时的时间。
在这里插入图片描述

1.子组件

<template>
	<view class="time">
	<view class="red-box" >{{days>=10?days:'0'+days}}</view>
		<view class="fz-12 color3" style="margin: 0 2px;"></view>
		<view class="red-box" >{{hours>=10?hours:'0'+hours}}</view>
		<view class="fz-12 color3" style="margin: 0 2px;"></view>
		<view class="red-box">{{minutes>=10?minutes:'0'+minutes}}</view>
		<view class="fz-12 color3" style="margin: 0 2px;"></view>
		<view class="red-box">{{seconds>=10?seconds:'0'+seconds}}</view>
		<view class="fz-12 color3" style="margin: 0 2px;"></view>
	</view>
</template>

<script>
	export default {
		props: {
			targetDate: {
				type: String,
				required: true
			}
		},
		data() {
			return {
				countdownInterval: null,
				days: 0,
				hours: 0,
				minutes: 0,
				seconds: 0
			};
		},
		mounted() {
			this.startCountdown();
		},
		beforeDestroy() {
			clearInterval(this.countdownInterval);
		},
		methods: {
			startCountdown() {
				this.updateCountdown(); // 先立即更新一次
				this.countdownInterval = setInterval(() => {
					this.updateCountdown();
				}, 1000);
			},
			updateCountdown() {
				const now = new Date();
				const target = new Date(this.targetDate);
				const duration = Math.max(0, target - now) / 1000;
				this.days = Math.floor(duration / 86400);
				this.hours = Math.floor((duration % 86400) / 3600);
				this.minutes = Math.floor((duration % 3600) / 60);
				this.seconds = Math.floor(duration % 60);
				if (duration <= 0) {
					clearInterval(this.countdownInterval);
					this.$emit('countdownFinished'); // 触发倒计时结束事件
				}
			}
		}
	};
</script>
<style lang="scss" scoped>
	.time {
		margin-top: 4rpx;
		display: flex;
		color: #ff0000;
		font-size: 22rpx;
		text-align: center;
		align-items: center;

		.red-box {
			font-size: 22rpx;
		}
	}
	.color3{
		color: #ff0000;
		font-size: 22rpx;
	}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值