我有一个网站,我想在特定时间(例如下午 3:35)重新加载,而不是在特定时间间隔(例如 5 分钟)之后重新加载。我该怎么做?
最佳答案
以下 JavaScript 代码片段将允许您在给定时间刷新:
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);
}
然后你可以添加一个脚本标签来调用refreshAt()
函数。
refreshAt(15,35,0); //Will refresh the page at 3:35pm
请注意,此代码将根据客户端本地时间 进行刷新。如果您希望它在特定时间而不考虑客户端的时区,您可以替换 get*()
和 set*()
(getTime() 除外
) 在时间对象上使用它们的 getUTC*()
和 setUTC*()
等价物,以便将其固定到 UTC。
关于javascript - 如何在特定时间自动重新加载网页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1217929/