You need to enable JavaScript to run this app. 如何使用Javascript实现每24小时自动将变量重置为0?含Chrome存储场景
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Javascript实现每24小时自动将变量重置为0?含Chrome存储场景

需求实现方案

首先明确场景差异:普通网页环境只能用原生JS实现,且依赖页面持续存活;Chrome扩展环境推荐用官方专属API实现,稳定性更高。

1. 原生Vanilla JS实现方案

适用场景:仅页面持续运行时生效,页面关闭后定时任务会失效
核心思路是先计算当前时间到下一个午夜的毫秒差,设置单次定时器触发重置操作,之后每24小时循环执行一次。
代码示例:

// 重置变量的核心逻辑
async function resetDailyVariable() {
  // 普通网页用localStorage的写法:
  // localStorage.setItem('yourVariableKey', '0')
  // Chrome扩展环境操作chrome.storage的写法:
  await chrome.storage.local.set({ yourVariableKey: 0 });
  console.log('变量已在午夜重置为0');
}

// 计算距离下一个午夜的等待时间
function getMillisecondsToMidnight() {
  const now = new Date();
  const midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0);
  return midnight.getTime() - now.getTime();
}

// 初始化定时任务
function initDailyReset() {
  const waitTime = getMillisecondsToMidnight();
  // 第一次到午夜触发
  setTimeout(() => {
    resetDailyVariable();
    // 之后每24小时触发一次
    setInterval(resetDailyVariable, 24 * 60 * 60 * 1000);
  }, waitTime);
}

// 页面加载/脚本初始化时调用
initDailyReset();

注意:该方案的定时器会受到页面休眠、浏览器内存回收、页面关闭的影响,准确性和可靠性较低,仅适合临时使用。

2. Chrome扩展最优实现方案(官方自带API)

Chrome提供了chrome.alarms API专门用于定时调度任务,不受扩展后台Service Worker休眠、浏览器后台运行的影响,是该需求的最优解,无需用户交互即可稳定触发。

前置配置(manifest.json)

首先需要在扩展的清单文件中声明所需权限:

{
  "manifest_version": 3,
  "permissions": ["alarms", "storage"],
  "background": {
    "service_worker": "background.js"
  }
}

核心代码(background.js)

// 扩展安装/更新时初始化定时闹钟
chrome.runtime.onInstalled.addListener(async () => {
  // 先移除已存在的同名闹钟避免重复
  await chrome.alarms.clear('dailyResetAlarm');
  // 创建每天午夜触发的闹钟
  const nextMidnight = new Date();
  nextMidnight.setHours(24, 0, 0, 0);
  chrome.alarms.create('dailyResetAlarm', {
    when: nextMidnight.getTime(),
    periodInMinutes: 24 * 60 // 每24小时重复一次
  });
});

// 监听闹钟触发事件
chrome.alarms.onAlarm.addListener(async (alarm) => {
  if (alarm.name === 'dailyResetAlarm') {
    // 重置存储的变量
    await chrome.storage.local.set({ yourVariableKey: 0 });
    console.log('午夜变量重置完成');
  }
});

该方案完全依托Chrome官方能力,可靠性极高,就算扩展后台被系统回收,到点也会自动唤醒扩展执行重置逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 10:51:03