【问题标题】:Automatic web-page refresh memory leak using XMLHttpRequest使用 XMLHttpRequest 自动刷新网页内存泄漏
【发布时间】: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 循环中设置断点的地方,看起来在右侧的“关闭”面板中有一个循环引用。有人看到这个问题吗?

我可以做些什么来深入挖掘并获得更多信息?

提前致谢!

【问题讨论】:

标签: javascript ajax json memory-leaks xmlhttprequest


【解决方案1】:

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

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

Bug:XMLHttpRequest 的实例不会被垃圾收集以防万一 你有实例的引用 或其他 [原文如此] COM 对象(对于 例如:DOM 节点等)在其 onreadystatechange 处理程序,因此 产生运行时内存泄漏。

【讨论】:

  • 感谢您的信息,克里斯!这看起来很有帮助。我计划在接下来的几周内实施新图书馆。我暂时退出了这个项目,但我会用我的结果来回应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-27
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
相关资源
最近更新 更多