jQuery内存泄漏重复.ajax调用 [英] jQuery memory leak with repeated .ajax calls

查看:158
本文介绍了jQuery内存泄漏重复.ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $(function(){

(function(){

var callee = arguments.callee;

$ .ajax({
url:'...',
success:function(){... setTimeout(callee,1000);},
error:function(){... setTimeout(callee,1000);}
});

))();

});内存泄漏仍然存在,即使成功/错误除了再次调用setTimeout之外什么都不做。我通过Windows任务管理器观察泄漏;如果页面仍处于打开状态,firefox.exe的内存使用情况会慢慢升高。对于这个代码的最终版本,我只需要每分钟更新一次,但是每秒一次就可以更快速地显示内存泄漏!

(注意:这看起来像这个问题非常类似的问题,但选定的答案没有出现迎合Firefox)

解决方案

我能够重现问题并解决它例如:

$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ $函数checkStatus
{
$ .ajax({
url:'...',
success:function(){... setTimeout(checkStatus,1000);},
error:function( ){... setTimeout(checkStatus,1000);}
});

}

checkStatus();

} );

每当您的匿名方法被调用时,会发生什么情况,它会创建一个变量并指定一个引用到它。给定足够的时间,这将填满内存。



这个解决方案只是传递相同的函数ref,而不是每次迭代创建一个新的函数。 $ b

I'm using the following pattern which is leaking memory in Firefox:

$(function() {

    (function() {

        var callee = arguments.callee;

        $.ajax({
            url: '...',
            success: function() { ... setTimeout(callee, 1000); },
            error: function() { ... setTimeout(callee, 1000); }
        });

    })();

});

The memory leak remains, even when success/error do nothing other than calling setTimeout again. I'm observing the leak via Windows Task Manager; if the page is left open, memory usage of firefox.exe slowly creeps up. For the final version of this code, I only need to update once a minute, but once-a-second demonstrates the memory leak much faster!

(Note: this looks like a very similar problem to this question, but the selected answer there doesn't appear to cater for Firefox)

解决方案

I was able to reproduce the problem and solved it as such:

$(function() 
{
    function checkStatus() 
    {
        $.ajax({
          url: '...',
          success: function() { ... setTimeout(checkStatus, 1000); },
          error: function() { ... setTimeout(checkStatus, 1000); }
        });

    }

    checkStatus();

});

What appears to happen is each time your anonymous method is called, it creates a variable and assigns a reference to it. Given enough time, this will fill up memory.

This solution just passes the same function ref around rather than creating a new one with each iteration.

这篇关于jQuery内存泄漏重复.ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆