I have researched quite a bit about this but mostly by piecing other questions together, which still leaves some doubt. In an app that does not refresh the browser page at any time and may live for quite a while (hours) without closing (assuming that refreshing a page or navigating to another would restart the js code), what’s the best way to ensure objects are released and that there’s no memory leak.
These are the specific scenarios I’m concerned about:
All of the code below is within a revealing module pattern.
mycode = function(){}()
variables within functions, I’m sure this one is collected by the GC just fine
function(){ var h = "ss";}
variables within the module, should g = null when it’s no longer needed?
var g;
function(){ g = "dd";}
And lastly the life of a jqXHR: is it cleaned up after it returns? Should it be set to null in all cases as a precaution whether kept inside a function or module?
If doing this, is it x cleaned up by the GC after it returns?:
function(){
var x = $.get();
x.done = ...;
x.fail = ...;
}
How about when doing this, will it also be cleaned up after x returns?:
var x;
function(){
x = $.get();
x.done = ...;
x.fail = ...;
}
Lastly, is there a way to cleanup all variables and restart a module without restarting the browser?
Yes.
Sure.
Various browsers have had bugs related to XHR that caused the
onreadystatechangeand anything it closed over to remain uncollectable unless the dev was careful to replace it with a dummy value (xhr.onreadystatechange = new Function('')) but I believe jQuery handles this for you.Global state associated with the page will take up browser memory until the page is evicted from the browser history stack.
location.replacecan help you here by letting you kill the current page and replace it with a new version of the same app without expanding the history stack.When you use the word “module”, that is not a term that has a well-defined meaning to the browser or its JavaScript interpreter so there is no way to evict a module and only a module from memory. There are several things that you have to worry about that might keep things in memory:
setIntervalandsetTimeoutcallbacks and everything they close over.Any scheme that is going to unload a module and only a module would need to deal with all of these and figure out which of them are part of the module and which are not. That’s a lot of different kinds of cleanup.