I'm sure this will be a d'oh for a number of people, and something I should
have known a long time ago, but I figured I'd share it just in case it helps
someone else.

 

I ran into a memory leak problem a few months back due to an incorrect use
of closures in my code.  I managed to fix it, but have very been nervous
about using them ever since, even to the point of writing complex
workarounds rather than just using a closure when it would have been
appropriate.

 

Anyway, (and here is the d'oh part), all I had to do was null out the
variables used in the closure and the crappy Internet Explorer garbage
collector would be able to clean it up, preventing memory leaks.

 

Example code snippet:

 

var el = $(this);

setTimeout(function()

{

    el.hide();

    el = null;

},1000);

 

I did some tests with sIEve with different types of closures, and so long as
I nulled out the context variables, I didn't get any memory leaks.

 

Of course, it is still best practice to only use closures when it is
appropriate, and NEVER by mistake, but so long as you null out the variable
that CAUSED the closure, it seems to handle the problem IE has with garbage
collection.

 

Thoughts?  Feedback?

 

JK

Reply via email to