繁体   English   中英

XMLHttpRequest + setTimeout =内存泄漏

[英]XMLHttpRequest + setTimeout = Memory leak

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

      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和一个outsetInterval来测试,但结果相同:

  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)

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM