如何在每个特定时间刷新图像? JavaScript

How to refresh images each specific time ? JavaScript

我有一个简单的 HTML 页面

<img src="http://www.hamqsl.com/solar101pic.php">

这张图片每天都会更新

如何让我的页面每天或每 12 小时更新一次此图片

我要JavaScript更新的原因 因为我在 HTML 小部件中使用它 哪个不会自行更新

setInterval(function() { location.reload(); }, 5000);

更新

我认为你的逻辑不会成功,因为浏览器在你打开它时开始计数,所以图像会在打开它 12 小时后发生变化,而不是在特定时间,所以你必须选择

  1. 设置图像 Url 在服务器端
  2. 为时钟上的每个小时分配图像

window.location.reload(true) 在不使用缓存版本的情况下强制重新加载页面。 (MDN)

你可以这样实现一个定时器:

setTimeout(function(){  
  window.location.reload(true);
},4.32e+7); // 12 hours refresh rate. This is the time, in milliseconds.

有关 setTimeout (MDN) 的更多信息。

您可以使用 Javascript 的 setTimeout 函数,它会在事件达到指定的计时器(以毫秒为单位)后触发事件:

setTimeout(function(){
    window.location.reload(1);
}, 3600);

或者您可以使用以下元标记(以秒为单位):

<meta http-equiv="refresh" content="3600" />

编辑:刚想到一个更好的方法。如何使用 jQuery 删除元素,然后再次重绘该元素?

您要手动更新图像的 link 吗?还是 URL 中的“101”递增?

如果 link 是静态的,除了某种数字整数,那么我会使用 JavaScript 将 HTML 注入您的网页。检查:

var imgHtml = '<img src="http://www.hamqsl.com/solar101pic.php">';
document.getElementById('tag-id').innerHTML = imgHtml

您可以使用Date.now() 函数获取纪元时间,然后使用MOD(%) 设置合适的时间间隔。这就是您获得 12 小时的方式。我会留给你找出答案。

this page 所述,只需使用缓存断路器重新加载您的图像即可:

const img = document.getElementById("myImage")

setInterval( () => {
   img.src = "http://www.hamqsl.com/solar101pic.php?" + new Date().getTime();
}, 1000*3600*12) // 12 hours in ms
<img id="myImage" src="http://www.hamqsl.com/solar101pic.php" />

通过在 URL 之后添加 ?randomstuff,您可以强制浏览器获取文件的新副本,因为它未被识别为在缓存中。