XMLHttpRequest + setTimeout =内存泄漏

时间:2013-04-07 02:55:50

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

我正在开发一个Chrome扩展程序,我努力尝试网络中的所有解决方案,但似乎没有人工作。我的jsscript只通过XMLHttpReq(XHR)消耗一个html(每个请求约13,30k)并解析响应,丢弃与某些正则表达式不匹配的所有内容。所有这一切都发生在XHR onload方法中的setTimeout内部并且似乎有效,但问题是在10分钟aprox之后出现的。当我看到记忆中发生的事情。 10分钟后,扩展内存从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和一个outter 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)

1 个答案:

答案 0 :(得分:0)

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

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

您可能希望研究jQuery,它为XHR提供了一个非常方便的框架工作,但我认为您可以通过将对setTimeout的调用移动到外部作用域,将其更改为setInterval并仅调用它来修复内存问题一次。

相关问题