VueJS实现带开始、暂停、继续、停止功能的正计时 续计时异常问题
问题根因
你当前的时间计算逻辑直接用当前时间戳减去计时器首次启动的初始时间戳,没有扣除暂停状态下的空白时长,所以暂停的5秒也被计入了总流逝时间,恢复计时时就会直接跳转到包含暂停时长的数值。
修复方案
你需要新增两个状态变量记录暂停相关的时间,调整时间计算逻辑扣除暂停时长即可:
- 新增
pauseStartTime:记录每次点击暂停按钮的时间戳 - 新增
totalPausedTime:累计所有暂停阶段的总时长 - 暂停时记录当前时间到
pauseStartTime - 恢复时计算本次暂停的时长,累加到
totalPausedTime后清空pauseStartTime - 计算已流逝时间时,统一减去累计的
totalPausedTime
核心代码修改示例
<script> export default { data() { return { isRunning: false, timer: null, // 初始启动时间戳 initialStartTime: null, // 暂停开始时间戳 pauseStartTime: null, // 累计总暂停时长(毫秒) totalPausedTime: 0, // 展示的时分秒 displayTime: '00:00:00' } }, methods: { // 首次启动计时器 startTimer() { this.isRunning = true this.initialStartTime = Date.now() this.totalPausedTime = 0 this.pauseStartTime = null this.runInterval() }, // 暂停计时器 pauseTimer() { this.isRunning = false clearInterval(this.timer) this.pauseStartTime = Date.now() }, // 恢复计时器 resumeTimer() { this.isRunning = true // 累加本次暂停的时长 this.totalPausedTime += Date.now() - this.pauseStartTime this.pauseStartTime = null this.runInterval() }, runInterval() { this.timer = setInterval(() => { // 计算实际流逝的秒数,扣除总暂停时长 const elapsedSeconds = Math.floor((Date.now() - this.initialStartTime - this.totalPausedTime) / 1000) // 转时分秒的逻辑保持不变 this.displayTime = this.formatSecondsToTime(elapsedSeconds) }, 1000) }, formatSecondsToTime(seconds) { const h = String(Math.floor(seconds / 3600)).padStart(2, '0') const m = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0') const s = String(seconds % 60).padStart(2, '0') return `${h}:${m}:${s}` } }, beforeUnmount() { clearInterval(this.timer) } } </script>
额外优化建议
如果需要更高的计时精度,可以把setInterval的间隔调整为100ms左右,避免1秒间隔下的延迟误差,时间计算逻辑不需要改动。
内容的提问来源于stack exchange,提问作者Hadi Ismanto
相关产品推荐
相关产品推荐

