gpt4 book ai didi

javascript - 设置第一次执行的超时时间

转载 作者:行者123 更新时间:2023-12-03 10:24:20 26 4
gpt4 key购买 nike

我使用此脚本每小时检索一个页面的新内容。

        (function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
setTimeout(worker, 3600000);
}
});
})();

它每 60 分钟加载一次内容,但我真正想要的是在每小时开始时加载新内容(即 8:00,然后在 9:00 再次加载)。如果我在一小时开始时第一次加载页面,我的代码是有用的,但如果我在一小时内(例如 7:45)第一次加载它,它会在 8:45 重新加载内容,依此类推。我如何改进我的代码,使其第一次重新加载应该在 15 分钟后发生,然后在每小时发生?如何更改 setTimeout 函数来实现我的目标?我找到了一段可以接近我的目标的代码,但我一直在思考如何将它集成到我的函数中:

function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes &&
now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}

最佳答案

您可以计算到下一小时的剩余毫秒数

function doNextHour(callback) {
// time now in milliseconds since 1970
var now = new Date().getTime();
var MS_IN_HOUR = 60 * 60 * 1000;
// remaining ms until next hour
var remaining = MS_IN_HOUR - (now % MS_IN_HOUR);
setTimeout(callback, remaining);
}

使用类似

    (function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
doNextHour(worker);
}
});
})();

确保您最初还调用了 worker() 来启动 cron 作业

关于javascript - 设置第一次执行的超时时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29477550/

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