如何在按钮点击时更新setInterval变量值及重置Cookie存储的定时器
我来帮你梳理下怎么搞定这个需求哈,核心要解决三个问题:让OK按钮能修改定时器的变量、避免多个定时器冲突、正确完成重置逻辑,还要把计时状态存在Cookie里。下面是具体的实现思路和代码:
1. 先写个简单的Cookie读写工具
方便咱们快速存/取计时值:
// 写入Cookie,默认1天过期,可按需调整 function setCookie(name, value, days = 1) { const date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); const expires = "expires=" + date.toUTCString(); document.cookie = `${name}=${value}; ${expires}; path=/`; } // 读取Cookie function getCookie(name) { const nameEQ = `${name}=`; const ca = document.cookie.split(';'); for(let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1); if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length); } return null; }
2. 封装定时器核心逻辑
把关键变量(定时器ID、初始时长、当前计时)放在全局/闭包里,让外部事件能访问到:
// 全局变量(用闭包封装会更优雅,这里先简化用全局) let intervalId = null; let initialDuration = 0; // 存初始时长,用于重置 let currentTimer = 0; function startTimer(duration) { // 保存初始时长 initialDuration = duration; // 优先从Cookie读取之前的计时,没有就用初始值 const savedTimer = getCookie('timerValue'); currentTimer = savedTimer ? parseInt(savedTimer, 10) : duration; // 先清除旧定时器,避免多个定时器同时跑 if (intervalId) clearInterval(intervalId); // 启动新定时器 intervalId = setInterval(function() { const minutes = parseInt(currentTimer / 60, 10); const seconds = parseInt(currentTimer % 60, 10); // 格式化时间(补零) const formattedMin = minutes < 10 ? `0${minutes}` : minutes; const formattedSec = seconds < 10 ? `0${seconds}` : seconds; // 这里可以加页面显示逻辑,比如把时间放到某个元素里 // document.getElementById('timer').textContent = `${formattedMin}:${formattedSec}`; // 把当前计时写入Cookie setCookie('timerValue', currentTimer); // 计时减一 currentTimer--; // 计时到点触发提示 if (currentTimer < 0) { clearInterval(intervalId); intervalId = null; // 弹出提示,点击OK后重置 if (confirm('时间到啦!点击OK重新开始')) { resetTimer(); } } }, 1000); } // 重置定时器的函数,供OK按钮调用 function resetTimer() { // 清除旧定时器 if (intervalId) clearInterval(intervalId); // 重置计时为初始值,写入Cookie currentTimer = initialDuration; setCookie('timerValue', currentTimer); // 重新启动定时器 startTimer(initialDuration); }
3. 调用示例
比如启动一个5分钟(300秒)的定时器:
// 启动300秒的定时器 startTimer(300);
关键细节说明:
- 定时器ID管理:
intervalId用来记录当前运行的定时器,重置前先清除,避免多个定时器同时执行导致计时混乱。 - Cookie持久化:每次计时更新都把
currentTimer写入Cookie,页面刷新后能自动恢复之前的计时状态(如果不需要恢复,去掉读取Cookie的逻辑即可)。 - 变量作用域:把
currentTimer和intervalId放在全局,这样提示框的OK回调或者其他按钮事件能直接修改这些变量完成重置。
内容的提问来源于stack exchange,提问作者Test1234
相关产品推荐
相关产品推荐

