【问题标题】:XMLHttpRequest + setTimeout = Memory leakXMLHttpRequest + setTimeout = 内存泄漏
【发布时间】:2013-04-07 02:55:49
【问题描述】:

我正在开发一个 chrome 扩展程序,我尝试了网络上的所有解决方案,但似乎没有一个有效。我的 jsscript 仅通过 XMLHttpReq(XHR) 消耗一个 html(每个请求大约 13,30k)并解析响应,丢弃与某些正则表达式不匹配的所有内容。所有这一切都发生在 XHR onload 方法中的 setTimeout 中,并且似乎有效,但问题出现在大约 10 分钟后。当我看到记忆中发生的事情时。 10 分钟后,扩展 mem 从 10mb 增长到 60。那么..会发生什么并且存在任何解决方案?我读到这是一个正常的增长,因为它是一个新的请求,并且垃圾收集器会在一段时间后运行(很晚),但对我来说是另一回事。提前致谢。

      var CHECK_TIME = 30000;  
      var request = new XMLHttpRequest();

      var checkLastPage = {
        url:"http://www.last.fm/inbox",
        inboxId:"inboxLink",
        lastAttempt:0,    
        init : function(){        
            request.onload = function(){
              checkLastPage.loadStuff(request);
              setTimeout(checkLastPage.init, CHECK_TIME);          
            } 
            request.open("GET",checkLastPage.url,false);
            request.send();
        },
        loadStuff:function(request){
            var node = checkLastPage.getInboxNode(request);
//...more code
        },
        getInboxNode:function(request){
            var htmlTemp = document.createElement('div');
                htmlTemp.innerHTML = request.responseText;   // Hack horrible para poder parsear el nodo importante                     
            var htmlResponse =  htmlTemp.getElementsByTagName('li');
            var relevantNode = null;
             for (var i = 0; i < htmlResponse.length; i++) {
                var node = htmlResponse[i];
                if(node.id == checkLastPage.inboxId){
                  relevantNode = node;
                }                
             }
             htmlResponse = null;
             htmlTemp = null;   
             return relevantNode;
        }, //...more code}

我还使用 JQUery 和外部 setInterval 进行了测试,但结果相同:

  var CHECK_TIME = 30000;         
  var checkLastPage = {
    url:"http://www.last.fm/inbox",
    inboxId:"inboxLink",
    lastAttempt:0,    
    init : function(){        
       $get(checkLastPage.url,function(data){
           console.log(data)
        }            
    }
    //more code ...
  }

  setInterval(checkLastPage.init,CHECK_TIME)

【问题讨论】:

    标签: javascript performance google-chrome-extension xmlhttprequest settimeout


    【解决方案1】:

    从回调方法中调用 setTimeout 可能不是一个好主意。

    我认为从回调例程中调用 setTimeout 可能会阻止浏览器正确收集垃圾。

    您可能想研究 jQuery,它为 XHR 提供了一个很好的便捷框架,但我认为您可以通过将 setTimeout 调用移至外部范围,将其更改为 setInterval 并仅调用它来解决内存问题一次。

    【讨论】:

    • "你应该知道 setTimeout 设置了一个间隔计时器:也就是说,它会周期性地触发它的动作,而不仅仅是一次。"这是不正确的。 setTimeout() 只触发一次。你在想setInterval()
    • 是的,我用 JQuery 和 setTimeout out of callback 以不同的方式对此进行了测试,但没有任何反应:(
    猜你喜欢
    • 2013-04-10
    • 2021-01-25
    • 1970-01-01
    • 2021-01-31
    • 2014-06-07
    • 2020-08-06
    • 2018-06-13
    • 2012-04-06
    • 1970-01-01
    相关资源
    最近更新 更多