当前位置: 首页 > news >正文

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>
http://www.lryc.cn/news/158016.html

相关文章:

  • java 实现访问者模式
  • JDK源码剖析之PriorityQueue优先级队列
  • TSINGSEE青犀AI视频分析/边缘计算/AI算法·人脸识别功能——多场景高效运用
  • 力扣(LeetCode)算法_C++——最大连续 1 的个数 III
  • 23062C++QT day2
  • React三属性之:props
  • 大数据安全 | (一)介绍
  • 软件工程的概念及其重要性
  • [足式机器人]Part3 变分法Ch01-2 数学预备知识——【读书笔记】
  • 【嵌入式开发 Linux 常用命令系列 7.1 -- awk 过滤列中含有特定字符的行】
  • 前端(十六)——Web应用的安全性研究
  • 无涯教程-JavaScript - BIN2HEX函数
  • Kafka环境搭建与相关启动命令
  • 【C++】类的封装 ② ( 封装最基本的表层概念 | 类对象作为参数传递的几种情况 )
  • Linux上安装FTP
  • C/C++使用GDAL库编程窍门之——通用可移植性库(Common Portability Library, CPL)
  • Linux container_of() 宏定义
  • 详解python中的序列类型---列表list
  • Unity 引擎中国版 “团结引擎” 发布
  • MindsDB为许多不支持内置机器学习的数据库带来了机器学习功能
  • 世界级黑客丨电脑犯罪界的汉尼拔
  • 【Matlab】Matlab实现数据的动态显示方法
  • 【Android】SDK安装及配置
  • ETCD详解
  • React笔记(五)hook
  • vue3中使用viewerjs实现图片预览效果
  • Erlang:Linux下使用observer、debugger进行调试
  • 2023 年高教社杯全国大学生数学建模竞赛-E 题 黄河水沙监测数据分析详解+思路+Python代码
  • 一生一芯10——verilator v5.008环境搭建
  • 信息化发展27