JQuery memory leak with .ajax callbacks

I use the following pattern that skips memory in Firefox:

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

A memory leak persists even when a success / error does nothing but call setTimeout again. I observe a leak through the Windows task manager; if the page is left open, firefox.exe memory usage is slowly increasing. For the final version of this code, I only need to update once a minute, but once a second it shows a memory leak faster!

(Note: this seems like a very similar problem for this question , but the selected answer there does not seem to be suitable for Firefox)

+7
jquery firefox memory-leaks
source share
3 answers

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(); }); 

It seems that every time you call an anonymous method, it creates a variable and assigns a link to it. With enough time, this will fill the memory.

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

+4
source share
Maybe you should try something like this?
 $(function() { (function() { var callee = arguments.callee; $.ajax( { url: '...', success: function() { ... setTimeout(function() { callee(); }, 1000); }, error: function() { ... setTimeout(function() { callee(); }, 1000); } }); })(); }); 

so instad of passing calle to setTimeout callback, pass an anonymous function that calls calle.

0
source share

Try calling out of these functions:

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

Thus, memory is allocated only once for the β€œcalled”, and not every time the functions are executed.

-3
source share

All Articles