如何修复JS毫秒级定时任务重复触发问题 避免高频发送服务器请求
修复方案
核心逻辑
保留5ms的定时器间隔保证精度,通过状态标记+触发后清除定时器的方式,实现单次指令发送,完全避免重复请求问题。
修复后代码
document.getElementById("arrTime").onclick = function () { clearInterval(attInterval); // 先清理上一次生成的arrInterval,避免多次点击产生多个并行定时器 if (typeof arrInterval !== 'undefined') clearInterval(arrInterval); let time = document.getElementsByClassName("relative_time")[0].textContent.slice(-8); const input = prompt("Set Arrival Time", time); const inputMs = parseInt(prompt("Set the milliseconds", "500")); const delay = parseInt(delayTime) + parseInt(inputMs); let arrivalTime; // 新增发送状态标记,初始为未发送状态 let hasSent = false; arrInterval = setInterval(function () { arrivalTime = document.getElementsByClassName("relative_time")[0].textContent; // 只有未发送过且时间满足条件时才执行后续逻辑 if (!hasSent && arrivalTime.slice(-8) >= input) { setTimeout(function () { document.getElementById("troop_confirm_submit").click(); // 发送完成后标记为已发送,同时清除定时器终止后续执行 hasSent = true; clearInterval(arrInterval); // 如果你需要的是暂停1秒后恢复运行而不是直接终止,可把上面两行替换为以下代码: // hasSent = true; // setTimeout(() => {hasSent = false}, 1000); }, delay); } }, 5); document.getElementById("showArrTime").innerHTML = input + ":" + inputMs.toString().padStart(3, "0"); document.getElementById("showSendTime").innerHTML = ""; };
关键改动说明
- 新增
hasSent状态变量,拦截同一轮时间匹配下的重复触发请求 - 单次指令触发完成后直接清理定时器,彻底终止后续定时判断逻辑,不会再生成重复请求
- 补全了原有代码缺失的变量声明,避免全局变量污染导致的未知异常
- 新增多次点击场景下的旧定时器清理逻辑,避免多个定时器并行运行产生异常
内容的提问来源于stack exchange,提问作者Michal
相关产品推荐
相关产品推荐

