0

我正在开发一个Chrome扩展,我努力尝试了网络中的所有解决方案,但似乎没有人工作。我的jsscript只通过XMLHttpReq(XHR)消耗一个html(每个请求大约13,30k)并解析响应,放弃与某些正则表达式不匹配的所有内容。所有这一切都发生在XHR onload方法中的setTimeout内,似乎可行,但问题出现在10分钟后。当我看到记忆中发生了什么。 10分钟后,扩展名mem从10mb增长到了60。那么什么情况会发生并存在任何解决方案?我读到这是一个正常的增长,因为它的一个新的请求和垃圾收集器运行一段时间后(这么晚),但为我的另一件事。提前致谢。XMLHttpRequest + setTimeout =内存泄漏

 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) 

回答

0

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

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

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

+1

”你应该知道setTimeout设置了一个间隔计时器:也就是说,它会定期触发它的动作,而不是一次。“ 这是不正确的。一个'setTimeout()'只会触发一次。你正在考虑'setInterval()'。 – idbehold 2013-04-07 12:02:49

+0

谢谢idbehold,你是对的 - 我纠正了我的答案。 – 2013-04-07 17:41:31

+0

是的,我用JQuery和setTimeout以不同的方式测试回调,但没有任何反应:( – Machinerium 2013-04-07 17:57:42