6

I'm writing a browser app that would be entirely AJAX-driven (first time in my life), that means:

  • it will be one page staying in the browser, loading program components as needed
  • browser history will be, well, none.
  • page will not be refreshed at all

My concern is what should I do about XMLHttpRequests, since I'm primarily C++ programmer, being taught that when you write a statement like

x = new XMLHttpRequest();

you need to delete it afterwards.

This question is entirely about memory management, whether this object, allocated with new stays in memory, even after it finishes it's "cycle" with readyState == 4 or is somehow released, freed, whatchacallit? Honestly, I have no idea at what point could it be freed, since the script creating these will be in HEAD and sit there potentially whole workday. Whether should I:

  • create one or several, reused objects of type XMLHttpRequest, program the app so that it won't need any more than this limit,
  • or it doesn't matter and I can allocate as many new XMLHttpRequests as I like?

Please include in your answers at what point and WHY those objects would be deleted, if they would at all, considering that the "frame" of my webpage will stay. Hope I made this question clear and thanks for any insightful answers.

EDIT:

Consider code (I removed many lines that were checking for unexpected return values for brevity) of an onClick event handler, that creates XMLHttpRequest and sends it:

function submitme(){  
  var p = document.getElementById('p'); //a text field being sent to server
  if(typeof p!='undefined' && p!=null){
    if(p.value!=""){
      //here XMLHttpRequest is created, this function
      //returns exactly object of this type or false, when failed
      var xhr=createXmlHttpRequestObject();
      if(xhr!=false){
        xhr.open("POST", "blablabla.php", true);
        xhr.onreadystatechange=function(){
          if(xhr.readyState==4){
             if(xhr.status==200){
               //result will be posted in this div below
               var adiv = document.getElementById('resultdiv');
               //extract the XML retrieved from the server
               xmlResponse = xhr.responseXML;
               //obtain the document element (the root element) of the XML structure
               xmlDocumentElement = xmlResponse.documentElement;
               //get the response text
               if(typeof adiv !='undefined' && adiv != null){
                  adiv.innerHTML=xmlDocumentElement.childNodes[0].firstChild.nodeValue;
               }
             }//end xhr.status
           }//end xhr.readyState
         };//end xhr.onreadystatechange
         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         xhr.send(p.value);
       }//end xhr!=false
     }//end p.value!=""
   }//end typeof p!='undefined'
 }//end submitme()

When XMLHttpRequest object instance is created, if this handler is fired, it is referenced once by xhr variable until handler finishes to execute. At this point there are how many references to this object instance? If I understand articles linked in your answers correctly, the answer should be none, and browser just waits for this request to turn readystate==4, finish executing onreadystatechange function and object is unreachable? Please confirm.

Kitet
  • 855
  • 1
  • 10
  • 20

5 Answers5

8

I have recently hit the same problem, and I have found all around the Internet that I should not have any concerns, because it is garbage collected. Well, you SHOULD have concerns, because it is quite easy to leave some references around, if you just got it work for the first time.

See this page:

http://javascript.info/tutorial/memory-leaks

and scroll down to "XmlHttpRequest..."

What it basically says:

IF you create a new xhr object every time (do not reuse them) AND capture each xhr object in the closure of the respective onreadystatechange callback THEN the xhr object will never be garbage collected, and the memory leak will ramp up.

To avoid this situation, use the this to access the xhr object (e.g. to check state), and get the xhr out of the closure.

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
Zoltan K.
  • 1,036
  • 9
  • 19
  • +1 I was doing tons of new XMLHttpRequest and got caught with this. You can also set the `onreadystatechange` to `null` to clean up – divillysausages Jun 25 '17 at 20:59
  • will you add a snipped example? I wonder how you would incorporate this into jquery's $.ajax method hmm – Coty Embry Jul 17 '19 at 18:08
  • Sorry, it has been a really long time since I had a good understanding of that code, and I only had it in pure JS. As I see, the link I provided is dead. However, this seems to be a good resource, and it uses JQuery (be advised that I skimmed through this article, and it seems to raise the correct red-flags, but I did go for an in-depth understanding - if it is not enough, let me know, and I extract some relevant code from my code-base): [Memory Leaks with XMLHttpRequest Objects](https://nullprogram.com/blog/2013/02/08/) – Zoltan K. Jul 17 '19 at 18:21
  • oh yeah bro, ive spent awhile on that site today acually. A really good article, thank you for your time. Looks like glenn's answer here https://stackoverflow.com/questions/6196946/jquery-ajax-functionality-accessing-the-xmlhttprequest-object helps me a lot should i do something like `this._xhr = null` to clear the ref out? – Coty Embry Jul 17 '19 at 19:16
  • @CotyEmbry I have zero familiarity, how this works with JQuery, but anyway I checked my code, which is pure JS, in in that case there was no need for any "nulling". In fact my original post was raised by the fact that virtually every XHR example I found had the issue of capturing the XHR object in a var in the handler function closure. Something like `xhr = new XMLHttpRequest(); xhr.onreadystatechange = (function() { return function() {callb(xhr);}; })();`, instead of `callb(this)`. I did not test it, but this should give the idea. – Zoltan K. Jul 17 '19 at 20:00
  • 1
    Also, I commented to myself that with `xhr.onreadystatechange = function() { _recvHeartBeatCb(this); };` `this` will be undefined, so the closure is required. However, using `this` in the closure will somehow not cause an issue with the garbage collector. Honestly, it is a bit suspicious to me right now, but I trust the old myself from the time I was writing this. If in doubt / cannot test, divillysausages' `xhr.onreadystatechange=null` would probably be the safest option. I think I did a ton of requests, and plotted the browser mem usage to test. – Zoltan K. Jul 17 '19 at 20:09
3

http://xhr.spec.whatwg.org/#garbage-collection - here is the answer to your question. This is part of specification (how it has to be implemented, but this is not 100% sure how it is implemented in all browsers), to understand it more deeply advice you to read the hole document

An XMLHttpRequest object must not be garbage collected if its state is OPENED and the send() flag is set, its state is HEADERS_RECEIVED, or its state is LOADING, and one of the following is true:

It has one or more event listeners registered whose type is readystatechange, progress, abort, error, load, timeout, or loadend.

The upload complete flag is unset and the associated XMLHttpRequestUpload object has one or more event listeners registered whose type is progress, abort, error, load, timeout, or loadend.

If an XMLHttpRequest object is garbage collected while its connection is still open, the user agent must terminate the request.

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
Vlad Nikitin
  • 1,929
  • 15
  • 17
2

JavaScript has an automatic built-in garbage collector.

You might want to read this article:

Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
  • Would you kindly look at my EDIT and confirm if I understood correctly? – Kitet Feb 04 '14 at 18:56
  • Seems correct to me. The only error I can tell is that there's a `)` missing in the 3rd line. You should also consider that a `xhr.status` value that is `200 <= x < 300` or `x = 304` is also valid. Check this: http://jsfiddle.net/57Pv7/ – Danilo Valente Feb 04 '14 at 19:05
  • I'm accepting this answer because it came 4 seconds before Quentin's, even though they are the same ;) – Kitet Feb 06 '14 at 10:48
1

JavaScript has garbage collection, just let the reference to the XHR object drop out of scope and it should get cleaned up automatically.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

XMLHttpRequest is nothing special as far as object lifetime is concerned. As any other object, it will be garbage-collected when you drop the last reference to it.

The possibly unusual or unfamiliar thing with XMLHttpRequest is the lifetime you are required to insure for an Ajax request to work properly.

Basically you need to have a live XMLHttpRequest object during all the lifetime of the underlying Ajax request.

Once the request is complete, you are free to delete the object or reuse it for another query.
This scenario is often used by people who do not want to bother with memory management :).

If you need to have multiple requests at once, you will need more than one XMLHttpRequest object.
In that case, you will probably want to manage the life time of each XMLHttpRequest object more precisely (either returning it to a pool of free request handlers or deleting it).

kuroi neko
  • 8,479
  • 1
  • 19
  • 43