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

如何使用JavaScript避免页面刷新时计时器重置

解决页面刷新后计时器重置的问题

要避免页面刷新时计时器重置,核心是把计时器的状态持久化存储,这里用浏览器的localStorage实现——它能在页面刷新甚至关闭浏览器后保留数据。

实现步骤

  • 页面初始化时,优先从localStorage读取之前保存的计时数据,初始化计时器变量并更新页面显示
  • 计时器运行过程中,每次时间更新时同步把状态保存到localStorage
  • 点击重置按钮时,清空localStorage里的计时数据,同时重置变量和页面显示

修改后的完整代码

JavaScript

// 页面加载时从localStorage读取数据初始化
let hours = parseInt(localStorage.getItem('timerHours')) || 0;
let mins = parseInt(localStorage.getItem('timerMins')) || 0;
let seconds = parseInt(localStorage.getItem('timerSeconds')) || 0;
let timex;

// 初始化页面显示
updateTimerDisplay();

$('#start').click(function(){
    startTimer();
});

$('#stop').click(function(){
    clearTimeout(timex);
});

$('#reset').click(function(){
    hours = 0;
    mins = 0;
    seconds = 0;
    // 清空localStorage数据
    localStorage.removeItem('timerHours');
    localStorage.removeItem('timerMins');
    localStorage.removeItem('timerSeconds');
    updateTimerDisplay();
});

function startTimer(){
    timex = setTimeout(function(){
        seconds++;
        if(seconds > 59){
            seconds = 0;
            mins++;
            if(mins > 59){
                mins = 0;
                hours++;
            }
        }
        // 更新显示并保存到localStorage
        updateTimerDisplay();
        saveTimerState();
        startTimer();
    }, 1000);
}

// 统一更新DOM显示的函数
function updateTimerDisplay(){
    $("#hours").text((hours < 10 ? '0' + hours : hours) + ':');
    $("#mins").text((mins < 10 ? '0' + mins : mins) + ':');
    $("#seconds").text(seconds < 10 ? '0' + seconds : seconds);
}

// 保存状态到localStorage的函数
function saveTimerState(){
    localStorage.setItem('timerHours', hours);
    localStorage.setItem('timerMins', mins);
    localStorage.setItem('timerSeconds', seconds);
}

CSS

#timer {
    font-size:150px;
    margin:0 auto;
    width:1000px;
}
#controls {
    margin:0 auto;
    width:600px;    
}
#controls button {
    font-size:24px;
}

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<center>
    <div id="timer">
        <span id="hours">00:</span>
        <span id="mins">00:</span>
        <span id="seconds">00</span>  
    </div>
    <div id="controls">
        <button id="start">Start</button>
        <button id="stop">Stop</button>
        <button id="reset">Reset</button>
    </div>
</center>

补充说明

  • localStorage存储的是字符串类型,读取时需要用parseInt转换为数字
  • 抽离了updateTimerDisplay和saveTimerState函数,简化重复逻辑,让代码更易维护
  • 页面加载时会自动恢复之前的计时状态,刷新后不会重置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:54:33