You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于jQuery实现计时器的停止与重置功能问题求助

修复重叠计时器问题的解决方案

原代码核心问题

  • 未保存setInterval返回的定时器ID,导致clearInterval无法正确终止旧定时器
  • 每次调用timerCount都会重新定义jQuery插件并创建新定时器,重置操作会同时运行多个定时器,造成内容重叠
  • 变量作用域混乱,参数与内部函数重名、全局变量滥用导致逻辑冲突

修复后的完整代码

jQuery 代码

// 全局变量:保存定时器ID、计时状态、当前计数
var timerId = null;
var running = false;
var currentCount = 0;

// 补零函数:将数字格式化为4位带前导零的字符串
function padNumber(n) {
    return n.toString().padStart(4, '0');
}

// 计时器核心逻辑
function timerCount() {
    if (running && !timerId) {
        // 启动定时器,每秒更新计数
        timerId = setInterval(function () {
            currentCount++;
            $("#timer").text(padNumber(currentCount));
        }, 1000);
    } else {
        // 停止定时器
        if (timerId) {
            clearInterval(timerId);
            timerId = null;
        }
    }
}

// 页面加载完成后启动计时器
$(document).ready(function () {
    running = true;
    timerCount();
});

// 停止计时器
function stoptimer() {
    running = false;
    timerCount();
}

// 重置计时器:停止旧定时器,重置计数,重新启动
function reset() {
    running = false;
    timerCount();
    currentCount = 0;
    $("#timer").text(padNumber(currentCount));
    running = true;
    timerCount();
}

// 键盘事件监听
$("body").keydown(function (e) {
    // 按下X键重置
    if (e.keyCode === 88) {   
        reset();
    }
    // 按下H键停止
    if (e.keyCode === 72) {   
        stoptimer();
    }
});

HTML 代码

<div id="timer"></div>

关键修改说明

  1. 保存定时器ID:新增timerId变量存储setInterval的返回值,确保每次都能精准清除旧定时器,避免多个定时器同时运行
  2. 独立补零函数:将补零逻辑抽离为独立函数padNumber,避免原代码中参数与函数重名的问题,同时使用padStart简化实现
  3. 优化计时器逻辑:timerCount仅负责启动/停止定时器,避免重复定义jQuery插件,每次启动前检查是否已有运行的定时器,防止重复创建
  4. 重置流程优化:重置时先停止旧定时器,再重置计数并更新显示,最后启动新定时器,确保状态完全重置
  5. 变量规范:使用currentCount代替原混乱的pad变量,明确变量用途,避免全局变量滥用

内容的提问来源于stack exchange,提问作者Fredrik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 23:20:33