【发布时间】:2011-04-21 00:14:45
【问题描述】:
您好,
我一直在为一些使用 8 位微控制器的硬件开发 Web 界面。该网页使用 HTML、javascript、JSON 和 XHR (XMLHttpRequest) 进行通信。我要做的是创建一个页面,该页面每 250 毫秒更新一次,使用 setInterval 来自控制器的新值,以便网页“实时”更新,使其更像用户的应用程序。
我已经让它大部分工作,但发现在我测试过的两种浏览器(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
}
供您参考,将从微控制器发送到浏览器的 JSON 文件看起来像这样...
{ "offset": "1500",
"detectorPosition": "1558",
"actuatorPosition": "120" }
这看起来像是代码中的“闭包”问题吗?
使用 Chrome 中的开发人员工具 (Ctrl-Shift-J),我注意到对 ParameterValues.json 文件(350B 大小)的多次调用,因为这是存储来自微控制器的值的 JSON 对象;但是浏览器是否以某种方式存储/缓存内存中的每个页面?
在我的 cmets 中附有该问题的两个屏幕截图。第二个是我在 XMLHttpRequest 循环中设置断点的地方,看起来在右侧的“关闭”面板中有一个循环引用。有人看到这个问题吗?
我可以做些什么来深入挖掘并获得更多信息?
提前致谢!
【问题讨论】:
-
Chrome 快照:i55.tinypic.com/fuyzaw.png
-
这是 Chrome 开发者工具的另一个屏幕截图。我在 XMLHttpRequest 循环中设置了一个断点,看起来右侧的“关闭”面板中有一个循环引用。 i54.tinypic.com/qyzprt.png
标签: javascript ajax json memory-leaks xmlhttprequest