如何实现每14天按日期触发4个指定函数且不受页面刷新影响
实现方案
核心逻辑是基于本地时间计算当前周期对应的执行函数,不需要依赖常驻的setInterval,页面刷新后重新计算即可得到正确结果,完全满足你的需求。
实现思路
- 先配置首次触发的基准日期,你可以自行替换为实际需要的首次执行日期
- 计算当前时间和基准日期的时间差,换算成两周的周期数,对4取模即可得到当前需要执行的函数序号
- 页面初始化时直接执行对应函数,如果需要页面常驻时自动切换,可加一个低频率的检查定时器即可(比如1小时检查一次,性能损耗可以忽略)
完整代码
JS代码
// 你可以替换为你需要的首次触发日期,这里示例为2024-01-01 00:00:00 const FIRST_TRIGGER_DATE = new Date('2024-01-01T00:00:00'); const TWO_WEEKS_MS = 14 * 24 * 60 * 60 * 1000; // 两周的毫秒数 let div1 = document.querySelector(".div1"); let div2 = document.querySelector(".div2"); let div3 = document.querySelector(".div3"); let div4 = document.querySelector(".div4"); const functions = [function1, function2, function3, function4]; function function1() { div1.style.display = "block"; div2.style.display = "none"; div3.style.display = "none"; div4.style.display = "none"; } function function2() { div1.style.display = "none"; div2.style.display = "block"; div3.style.display = "none"; div4.style.display = "none"; } function function3() { div1.style.display = "none"; div2.style.display = "none"; div3.style.display = "block"; div4.style.display = "none"; } function function4() { div1.style.display = "none"; div2.style.display = "none"; div3.style.display = "none"; div4.style.display = "block"; } // 计算当前应该执行的函数 function runCurrentFunction() { const now = Date.now(); // 如果当前时间还没到首次触发日期,默认执行第一个,可按需调整 if (now < FIRST_TRIGGER_DATE.getTime()) { function1(); return; } // 计算过了多少个两周 const diffMs = now - FIRST_TRIGGER_DATE.getTime(); const periodCount = Math.floor(diffMs / TWO_WEEKS_MS); // 对4取模得到当前要执行的函数索引 const currentIndex = periodCount % 4; functions[currentIndex](); } // 页面加载时立即执行一次 runCurrentFunction(); // 可选:如果需要页面开着的时候自动切换,加一个低频率定时器,每小时检查一次 setInterval(runCurrentFunction, 60 * 60 * 1000);
HTML代码和原有代码一致,无需修改
<div class="div1"> 1 </div> <div class="div2"> 2 </div> <div class="div3"> 3 </div> <div class="div4"> 4 </div>
注意事项
- 基准日期
FIRST_TRIGGER_DATE请自行修改为你实际需要的首次触发时间 - 因为使用本地时间,用户修改本地时钟会影响执行结果,符合你说的精度要求不高的场景
- 所有逻辑基于本地计算,不需要服务端支持,刷新页面不会影响执行逻辑
内容的提问来源于stack exchange,提问作者Bessonniy
相关产品推荐
相关产品推荐

