tags:

views:

63

answers:

3

Quick question.

I have a js function which gets called on the page every few seconds. It's an ajax update thing.

Being a function, I declare local variables. I don't want to use closures or global variables for various reasons.

I'd never considered this, but do I need to release/clear the variables at the end of the function to release memory or will js do this for me automatically ?

Thanks

+2  A: 

Variables are released once they are out of scope, in your case, the local variables that are declared inside your function will be automatically freed by js garbage collector, you don't have to worry about them.

Mahesh Velaga
A: 

Javascript has automatic garbage collection. You don't need to deallocate anything.

Max Shawabkeh
+1  A: 

Generally, no. Variables declared with var are local and are garbage collected when you return. If you omit the var then the variables are global, and using the delete keyword may be useful for global variables in some instances, but generally it's good practice to declare all variables with var anyway to not pollute the window namespace.

delete can be useful when using prototype-based inheritence though, e.g:

function myclass() {
    this.variable = 'myvalue'
    ...
    delete this.variable // finished with this variable
}
var inst = new myclass()

Bear in mind that if inst is deleted or becomes out of scope (garbage collected) all the attributes in it will be deleted as well. delete can also be useful for deleting items from hash tables:

var d = {}
d['blah'] = 'myvalue'
...
delete d['blah']

There are some browser-specific garbage collection bugs. IE sometimes has problems cleaning attributes in DOM elements and closures etc for example, though many of these problems have been reduced in IE8 I believe.

David Morrissey
Thanks for that. Can I follow you up on that IE bug. I'm actually doing that as well I think. I've a global array which is being reset with each ajax update. At the end of each cycle, I delete the div that contained the js array update from ajax (I need to post js to a div rather than accept the variables directly. It's complicated) and clear the array using xx = []; ready for the next cycle. Works fine except that after half hour or so IE8 falls over. With respect to your comment - what's a better way of clearing the array ? (note I've no proof this is the IE8 crash, but...)
Bob
I'd recommend reading http://msdn.microsoft.com/en-us/library/Bb250448 if the problem is IE-specific - chances are it's one of those issues. If it's actually crashing IE8 (not just displaying an "out of memory" message) it may not be memory related - I've never seen any memory issues do that, but I could be wrong. It could be any number of issues though, I'd really need to look at more code to get an idea.
David Morrissey