首页 > 解决方案 > 循环重新加载图像(JavaScript / HTML)

问题描述

我有一个 Python 脚本,每隔几秒钟就会更改一次图像,我需要在网站上显示该图像,而用户不必每隔几秒钟重新加载一次页面。我不是最擅长网页设计的,因此我们将不胜感激。

我试过这段代码:

function refreshImage(imgElement, imgURL){    
  // create a new timestamp 
  var timestamp = new Date().getTime();  

  var el = document.getElementById(imgElement);  

  var queryString = "?t=" + timestamp;    

  el.src = imgURL + queryString;    
}    

while (true){
  refreshImage(cameraFeed, "image.jpg")
}    

在一个循环中,但我无法让它工作。

如果有人可以帮助我,将不胜感激。

标签: javascripthtml

解决方案


正如Ozgur Sar在评论中建议的那样,您可以使用setInterval(). 例如像这样:

const refreshImage = (imgElement, imgURL) => () => 
  imgElement.src = imgURL + "?" + new Date().getTime();

const cameraFeed = document.querySelector(".cameraFeed");
setInterval(refreshImage(cameraFeed, "https://loremflickr.com/320/240"), 3000);
<img class="cameraFeed" src="https://loremflickr.com/320/240"/>


另一种方法,如果您不想使用 setInterval 在某个确切时间刷新图像,则使用提供全双工通信通道的Web 套接字。您可以使用在PythonJavaScript中都可以实现的 socket.io 。仅当您的 Python 脚本要求执行此操作时,它才会重新加载图像。


推荐阅读