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

如何防止HTML+JavaScript实现的秒表在页面刷新时重置

实现方案

核心思路是使用浏览器内置的localStorage持久化存储计时状态,页面加载时读取存储数据恢复状态,即可实现刷新不重置。需要修改的逻辑如下:

  • 页面初始化时优先读取localStorage中存储的计时数据、运行状态,替代默认的0值
  • 每次计时更新时同步写入最新的计时数据到localStorage
  • 清除计时时同时清空localStorage中的对应存储项
  • 停止计时时同步更新存储的运行状态
var h1 = document.getElementsByTagName('h1')[0],
    start = document.getElementById('start'),
    stop = document.getElementById('stop'),
    clear = document.getElementById('clear'),
    // 初始化时优先读取本地存储的数据
    seconds = parseInt(localStorage.getItem('stopwatch_seconds')) || 0,
    minutes = parseInt(localStorage.getItem('stopwatch_minutes')) || 0,
    hours = parseInt(localStorage.getItem('stopwatch_hours')) || 0,
    isRunning = localStorage.getItem('stopwatch_running') === 'true',
    t;

// 初始化渲染时间
updateTimeDisplay();

function add() {
    seconds++;
    if (seconds >= 60) {
        seconds = 0;
        minutes++;
        if (minutes >= 60) {
            minutes = 0;
            hours++;
        }
    }
    updateTimeDisplay();
    // 同步存储最新计时数据
    saveToLocalStorage();
    timer();
}
function timer() {
    t = setTimeout(add, 1000);
}

// 新增:更新时间展示的公共方法
function updateTimeDisplay() {
    h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
}

// 新增:存储数据到localStorage
function saveToLocalStorage() {
    localStorage.setItem('stopwatch_seconds', seconds);
    localStorage.setItem('stopwatch_minutes', minutes);
    localStorage.setItem('stopwatch_hours', hours);
    localStorage.setItem('stopwatch_running', isRunning);
}

// 如果上次退出时秒表正在运行,刷新后自动继续计时
if (isRunning) {
    timer();
}

/* Start button */
start.onclick = function() {
    if (!isRunning) {
        isRunning = true;
        saveToLocalStorage();
        timer();
    }
};

/* Stop button */
stop.onclick = function() {
    clearTimeout(t);
    isRunning = false;
    saveToLocalStorage();
}

/* Clear button */
clear.onclick = function() {
    h1.textContent = "00:00:00";
    seconds = 0; minutes = 0; hours = 0;
    isRunning = false;
    // 清空本地存储
    localStorage.removeItem('stopwatch_seconds');
    localStorage.removeItem('stopwatch_minutes');
    localStorage.removeItem('stopwatch_hours');
    localStorage.removeItem('stopwatch_running');
}

注意:localStorage是浏览器本地存储,仅在当前设备的当前浏览器生效,清空浏览器缓存会导致存储的计时数据丢失。如果需要跨设备同步计时,需要对接后端接口将数据存储到服务端。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:12:00