gpt4 book ai didi

javascript - setInterval 可以随时间漂移吗?

转载 作者:搜寻专家 更新时间:2023-11-01 00:02:38 25 4
gpt4 key购买 nike

我有 2 个 node.js 网络服务器。我在网络服务器中缓存数据。我根据系统时间同步缓存加载/清除。我已经完成了所有主机的时间同步。

现在我使用以下代码每 15 分钟清除一次缓存:

millisTillNexthour = "Calculate millis remaining until next hour"

setTimeout(function() {
setInterval(function() {
cache.clear();
}, 60000*15);
}, millisTillNexthour);

我的预期是,即使这个进程一直运行,缓存也会在一天中的每个小时的第 15 分钟清除一次。

我的问题是:setInterval 会随时间漂移吗?

例如:现在它在 10:00 10:15 10:30 10:45 11:00 ...... 清除缓存

setInterval 应该在系统时间 10:15 清除缓存,而不是系统时间 10:15,而是在系统时间 10:20 执行,这会发生吗?

我不确定这是如何工作的。请说明一下。我希望我能很好地解释我的问题。

最佳答案

我可能来晚了一点,但这就是我解决这个特殊时间滑动问题的方法,使用递归调用的 setTimeout() 函数而不是使用 setInterval()。

var interval = 5000;
var adjustedInterval = interval;
var expectedCycleTime = 0;

function runAtInterval(){
// get timestamp at very start of function call
var now = Date.now();

// log with time to show interval
console.log(new Date().toISOString().replace(/T/, ' ').replace(/Z/, '') + " runAtInterval()");

// set next expectedCycleTime and adjustedInterval
if (expectedCycleTime == 0){
expectedCycleTime = now + interval;
}
else {
adjustedInterval = interval - (now - expectedCycleTime);
expectedCycleTime += interval;
}

// function calls itself after delay of adjustedInterval
setTimeout(function () {
runAtInterval();
}, adjustedInterval);
}

在每次迭代中,该函数都会根据先前计算的预期时间检查实际 执行时间,然后从“interval”中扣除差值以生成“adjustedInterval”。这种差异可能是正数也可能是负数,结果表明实际执行时间往往在“真实”值 +/- ~5 毫秒左右波动。

无论哪种方式,如果你有一个每分钟执行一次的任务,并且你运行它一整天,使用这个函数你可以预期 - 对于一整天 - 每个小时都会有 60 次迭代发生。您不会遇到偶尔的一小时只得到 59 个结果的情况,因为最终整整一分钟都已经过去了。

关于javascript - setInterval 可以随时间漂移吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18167059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com