Saturday, July 16, 2011

Browser/Javascript Memory leaks with setTimeout

It's been some time since I have been working on the OpenAnimator project, but recently I observed a strange memory leak. After drilling down into a lot of the javascript, I found the problem with a snippet of code that was something like this:


a = function() {
    try {
       
    setTimeout('a()',1);
    }catch(e) { error(e); }
};
a();

At first look this looks like a fairly, okay bit of code, and not any variables were being created except the setTimeout call. After a lot of google hunting here is what I have now:

a = function() {
    try {
       
    setTimeout(function() {a();},1);
    }catch(e) { error(e); }
}
a();


Apparently this solved the problem (atleast it appears so now). I am still not able to figure out why there was a problem with the earlier code. the 'a()' is causing a implicit eval to be executed, but how that leads to memory leaks is still unknown to me. I hope I'll get this one someday.

No comments:

Post a Comment