0

Is this a good way to garbage collect

function getFile() {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        //do stuff
        delete(xhr)
    };
}

and then call getFile() a couple of times

(I've edited it to use a function)

How would I get rid of xhr when it's done. I'm just a bit confused on whether its ok to remove xhr from within a function of itself

Tarang
  • 75,157
  • 39
  • 215
  • 276

1 Answers1

2

You should use scoping to do the trick for you. In JavaScript scope is defined by the function statement. Variables that are defined within a function will be deleted automatically when the function goes out of scope (and you did not use the variable in a closure)

So in your case:

function scope() {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    //do stuff
  };
}
Koen Peters
  • 12,798
  • 6
  • 36
  • 59
  • Yes my xhr request is already in a function, I guess its the bit of whether this type of structure is ok. – Tarang May 20 '12 at 12:49
  • I can still access the xhr variable in the chrome javascript console though besides it being scoped in a function, is this a characteristic of the console or it it gone? – Tarang May 20 '12 at 12:52
  • I would omit the delete here and trust the scoping of JavaScript :) More on the delete statement here: http://stackoverflow.com/questions/742623/deleting-objects-in-javascript – Koen Peters May 20 '12 at 12:52
  • Well, it should not be accessible if it is not in scope... So there is something fishy. Try to rename the xhr variable so you can be sure that it is your xhr that is being displayed in the console – Koen Peters May 20 '12 at 12:53
  • Ill have to look at this maybe theres a xhr declared out of scope somewhere its quite a large file – Tarang May 20 '12 at 13:02