闹钟点击触发的Countdown功能无法正常停止,停在-1:0而非预期0:00求解决
问题根因
- 停止判断时机后置,代码逻辑为先渲染时间文本再判断是否终止定时器,哪怕剩余时间已经小于0,也会先计算出异常时间值渲染到页面,再清除定时器
- 秒数计算使用
Math.round()存在舍入偏差,剩余毫秒数不足500时会被舍为0、超过500时会进1,容易触发边界计算错误 - 未提前拦截剩余时间为负的场景,负的时间戳经过
Math.floor()计算分钟时会直接得到-1,最终渲染出-1:0的异常文本
修复方案
调整逻辑顺序,先判断是否到期,到期直接终止定时器并渲染00:00的最终值,同时替换秒数计算方法避免舍入误差,补充前导零格式化逻辑优化显示效果,另外新增重复点击防护避免同时启动多个定时器。
修复后JavaScript代码
function startTimer() { // 重复点击防护,清除已有的倒计时定时器 if (window.countdown) clearInterval(window.countdown); let startTime = new Date().getTime(); // 原代码5*1*1000为5秒,若需要5分钟倒计时可修改为5*60*1000 let fiveMinutes = 5 * 60 * 1000; let endTime = startTime + fiveMinutes; // 显式获取DOM节点,避免全局变量污染 const timer = document.getElementById('timer'); window.countdown = setInterval(function() { let timeLeft = endTime - new Date().getTime(); // 优先判断是否到期,到期直接终止流程 if (timeLeft <= 0) { clearInterval(window.countdown); timer.innerHTML = '00:00'; return; } let minutes = Math.floor(timeLeft / (1000 * 60)); // 改用Math.floor避免舍入误差 let seconds = Math.floor((timeLeft / 1000) % 60); // 补前导零,保证显示为两位数字 minutes = String(minutes).padStart(2, '0'); seconds = String(seconds).padStart(2, '0'); timer.innerHTML = `${minutes}:${seconds}`; }, 1000); }
HTML代码优化(可选)
原img标签存在冗余属性,可调整为标准写法:
<div class="timer center margin-top" id="timer"> 00:05 </div> <div class="button center"> <img onclick="startTimer()" src="img/btn.png" alt="启动按钮"> </div>
内容的提问来源于stack exchange,提问作者Codenix-1349
相关产品推荐
相关产品推荐

