运行 重复 javascript 提取请求正在快速填满浏览器内存。有没有办法防止这种情况?

Running repeating javascript fetch requests is filling up browser memory quickly. Is there a way to prevent this?

我正在构建一个网页,用于显示包含图像的实时事件流。为此,我决定尝试使用 javascript 运行ning 客户端和下面的代码每 1 秒从我的 API 端点获取数据(然后更新 html 相应地)。我注意到每个获取请求的结果都保存在内存中,这将很快填满浏览器内存,特别是如果 运行 按计划持续几个小时或一整天。

我在互联网上搜索过,发现我可以将创建的对象设置为 null 以将它们标记为可以安全清除以供垃圾收集器使用,但我是 javascript 的新手,我不确定where/what 实际设置等于 null。你知道我应该在下面的代码中将什么设置为 null 吗?

如果有任何其他解决方案,将不胜感激指导。

代码: 编辑:删除 setTimeout(1) - 仍然得到上面概述的相同行为

let myHeaders = new Headers();
myHeaders.append("xxxx", "xxxxxx");
myHeaders.append("Content-Type", "text/plain");

let raw = "{x:x}";

let requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

function printResult(result){
    console.log(result);
}

function getLatestRecords(){
    fetch("https://xxxx.xxxx.com", requestOptions)
      .then(response => response.json())
      .then(result => printResult(result))
      .catch(error => console.log('error', error));

    //setTimeout(1)
}

let interval = setInterval(
    function() {
        getLatestRecords()
    },
    1000
);

似乎正在为每次提取创建数据对象:

不清楚这是否与您的内存泄漏有关,但您正在以一种奇怪的方式使用 setTimeoutsetTimeout 用于安排在一定毫秒数后调用的回调; setTimeout(1) 是未定义的行为。

由于您的意图是让您的提取请求在 1 秒后被取消,因此您需要改为这样做:

function getLatestRecords(){
    var controller = new AbortController();
    setTimeout(() => controller.abort(), 1000);
    return fetch("https://xxxx.xxxx.com", { ...requestOptions, signal: controller.signal })
        .then(response => response.json())
        .then(result => printResult(result))
        .catch(error => console.log('error', error));
}