gpt4 book ai didi

javascript - 使用 XMLHttpRequest 自动网页刷新内存泄漏

转载 作者:行者123 更新时间:2023-11-30 06:06:53 34 4
gpt4 key购买 nike

你好,
我一直在为一些使用 8 位微 Controller 的硬件开发网络界面。该网页使用 HTML、javascript、JSON 和 XHR (XMLHttpRequest) 进行通信。我想要做的是创建一个页面,使用 setInterval 使用来自 Controller 的新值每 250 毫秒更新一次,以便网页“实时”更新,让用户感觉它更像是一个应用程序。

我已经让它的大部分工作正常,但发现在我测试过的两种浏览器(IE 和 Chrome)的代码中某处存在内存泄漏。

我已经在线研究过这个问题,似乎其他人也遇到过同样的问题,我尝试实现不同的修复方法但没有成功。

这里有一些代码快照,希望能更好地解释事情,我已经修改了变量,因此它们在没有看到完整应用程序的情况下也更有意义。

// start the pageRefreshTimer to update values
var pageRefreshTimer = window.setInterval(updateValues, 250);

// Standard XHR opener
HTTP.getText = function(url, callback) {
var request = HTTP.newRequest(); // Searches array of standard XMLHttpRequest functions to try, code not shown...
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
callback(request.responseText) // responseText becomes JSONText below
}
}
request.open("GET", url);
request.send(null);
}

// Function that is constantly refreshed by HTML page to simulate real-time application
updateValues = function(parameter, value) {

newURL = newURL + "?" + parameter; // newURL is defined elsewhere in the code...

// Send the url and create the JSONObject
HTTP.getText(newURL, function(JSONText) {
var JSONObject = eval('(' + JSONText + ')'); // Specific notation for JSON

// Load object values into Javascript variables
Controller.detectorPosition = JSONObject.detectorPosition;
Controller.offset = JSONObject.offset;
Controller.actuatorPosition = JSONObject.actuatorPosition;
});

delete JSONObject; // My attempt at manual garbage collection, didn't resolve the memory leak
}

供您引用,将从微 Controller 发送到浏览器的 JSON 文件看起来像这样......

{ "offset": "1500", 
"detectorPosition": "1558",
"actuatorPosition": "120" }

这看起来像是代码中“闭包”的问题吗?

使用 Chrome 中的开发人员工具 (Ctrl-Shift-J),我注意到有多个对 ParameterValues.json 文件(350B 大小)的调用,因为这是存储来自微 Controller 的值的 JSON 对象;但是浏览器是否以某种方式在内存中存储/缓存每个页面?

我的评论中附有该问题的两个屏幕截图。第二个是我在 XMLHttpRequest 循环中设置断点的地方,看起来右侧的“关闭”面板中有一个循环引用。有人发现这有问题吗?

我该怎么做才能更深入地挖掘并获取更多信息?

提前致谢!

最佳答案

有一个 Google 代码项目创建了 XMLHttpRequest 的跨浏览器实现。 .他们还维护一个小列表 native XMLHttpRequest bugs这可能对您有用。

以下错误似乎可能适用于您的情况:

Bug: The instance of XMLHttpRequest doesn't get garbage collected in case you have a reference to the instance or to an other [sic] COM object (for example: DOM Node etc.) in its onreadystatechange handler, thus producing runtime memory leaks.

关于javascript - 使用 XMLHttpRequest 自动网页刷新内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3858917/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com