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