我有一个 chrome 扩展的 JavaScript 函数,我需要以精确的 5 分钟间隔运行一次,与当前时间同步。例如,它应该在 5:00、5:05、5:10 等运行,无论脚本何时开始运行。
这是我正在尝试实施的方法:
Calculate the delay until the next 5-minute mark.
Use setTimeout to call the function at the next 5-minute mark.
Set up a setInterval to call the function every 5 minutes after the initial timeout.
Here is a simplified version of the code to demonstrate the issue:
function myFunction() {
console.log("Function executed at:", new Date().toLocaleTimeString());
}
function checkTimeAndRunMainFunction() {
let now = new Date();
let minutes = now.getMinutes();
let seconds = now.getSeconds();
if (seconds === 0 && minutes % 5 === 0) {
// Run the main function immediately
myFunction();
}
}
function calculateDelayToNextFiveMinuteMark() {
let now = new Date();
let millisecondsUntilNextFiveMinuteMark = (5 - (now.getMinutes() % 5)) * 60 * 1000 - now.getSeconds() * 1000 - now.getMilliseconds();
return millisecondsUntilNextFiveMinuteMark;
}
// Set an initial timeout to synchronize with the next 5-minute mark
setTimeout(function() {
checkTimeAndRunMainFunction();
// Set an interval to check the time every 5 minutes after the initial call
setInterval(checkTimeAndRunMainFunction, 5 * 60 * 1000);
}, calculateDelayToNextFiveMinuteMark());
我面临的问题是 setInterval(checkTimeAndRunMainFunction, 1000);从用户运行代码的那一刻开始计算每一秒,并且它与实际时钟的秒数不同步,导致条件 if (秒 === 0 && 分钟 % 5 === 0) 无法精确满足。
如何确保我的函数准确地在 5 分钟标记处运行(例如 5:00、5:05、5:10),无论脚本何时开始运行?
这里是每 5 分钟运行一次的简单脚本,并在每次运行时调整下一次开始时间
(function loop () {
let date = new Date();
let sec = date.getSeconds();
setTimeout(async () => {
console.log(date)
// your code here
loop();
}, (300 - sec) * 1000);
})();