javascript - 循环重新加载图像(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")
}
在一个循环中,但我无法让它工作。
如果有人可以帮助我,将不胜感激。
解决方案
正如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 套接字。您可以使用在Python和JavaScript中都可以实现的 socket.io 。仅当您的 Python 脚本要求执行此操作时,它才会重新加载图像。
推荐阅读
- c++ - c++ windows窗体焦点按钮
- mysql - Mysql限制偏移量变慢,偏移量值大
- mysql - UndefinedFunction:函数timediff(time with time zone, time with time zone)不存在
- c# - 根据置信度过滤单词
- angular - Angular Async Pipe 未正确更新
- r - 如何使数据框标签成为R中的列和拆分列?
- python - 如何使用循环为从 csv 导入的许多类似列创建名称相似的字符串?
- c - C:外部变量声明并包含守卫
- azure - 您如何以编程方式删除资源组中除特定资源之外的所有内容?
- javascript - Javascript 文件适用于一个 HTML 文件,但不适用于另一个