使用javascript's settimeout加载图像时内存泄漏

Memory leak when loading images with javascript's settimeout

本文关键字:图像 加载 内存 泄漏 settimeout javascript 使用      更新时间:2023-09-26

我设置了一种监控系统,相机每秒拍摄一张照片,并将这张照片发送到服务器,在服务器上它会覆盖前一张照片。在客户端,我有一个简单的javascript与settimeout每秒加载此图像

$("img").attr("src", "http://mysite/image.jpg?randomString="+new Date().getTime());

但是这会导致内存泄漏并最终导致页面崩溃。怎样才能避免这种情况呢?缓存是问题所在吗?浏览器是否缓存每一个新图像,每秒钟,这是内存泄漏的原因?

可能是一个缓存问题,因为浏览器可能缓存所有这些图像,因为它们每次都有新的图像名称(这应该不会导致崩溃)。

在这种情况下,在头文件中设置这些缓存指令,看看它是否解决了问题:

<!-- disable caching on proxy servers -->
<meta http-equiv="pragma" content="no-cache">
<!-- set expiration date to "immediately" -->
<meta http-equiv="expires" content="0">
<!-- instruct the browser to not cache the webpage -->
<meta http-equiv="cache-control" content="no-cache" />

另一方面,可能是另一个问题是你的javascript。如果服务器不能及时处理http请求,就会在浏览器中排队等待大量未解析的http请求。尝试将超时设置为5秒(= 5000毫秒)。

第三种可能的解决方案是使用纯javascript操作图像,以消除jQuery内存泄漏的可能性。

// cache the element once
var img = document.querySelector("img");
// use in setTimeout (Don't create a new Time Object on every call):
img.src = "/image.jpg?randomString="+Date.now();