Hi all,

I've written some functions that seem to be able to handle parallel AJAX requests. However, I am not sure if they would work under all circumstances.

My idea was to create a separate object for each AJAX request in order to bind the right handler function to the appropriate .onreadystatechange. I have used an array to store references to the created objects so that they would not be garbage collected as long as needed (see the lines commented out below). I have noticed, however, that everything works nicely even if I don't save these references -- so, with these lines commented out.

My question basically is whether it is safe to do so, and what prevents these objects from being deleted by the garbage collector. As both the event and the handler function appear to be in the same object, I think it will not stop the garbage collector.

In my code, ajax_req() is called to make a request; it will create the new ajax_abs object whose constructor takes care of the rest.

// ajaxrequests=new Array();

function ajax_abs(method,page,str,dest,todo,myno){
  function init(){
    var obj=false;
    try{
      obj=new ActiveXObject("Msxml2.XMLHTTP");
    }catch(err1){try{
      obj=new ActiveXObject("Microsoft.XMLHTTP");
    }catch(err2){try{
      obj=new XMLHttpRequest();
    }catch(err3){
      alert(message.ajaxerr);
    }}}
    return obj;
  }
  
  function ajaxhandler(){
    if(xmlhttp.readyState==4){
      switch(todo){
        (...)
      }
      // freeing object
      // delete(ajaxrequests[myno]);
    }
  }

  var xmlhttp=init();
  xmlhttp.onreadystatechange=ajaxhandler;

  xmlhttp.open(...);
  xmlhttp.send(...);
}

function ajax_req(method,page,str,dest,todo){
  var myno=0;
  // while(ajaxrequests[myno]){ myno++; }
  // ajaxrequests[myno]=
  new ajax_abs(method,page,str,dest,todo,myno);
}

Furthermore, is it possible to tell the interpreter after the request succeeds, that now it should garbage-collect the object? Just to be nice...

Thanks very much in advance!

The implementation of the Javascript interpreter is really up to the browser. Technically nothing should be garbage collected until a page is closed because of javascript's lexical scoping but as I said its up to the browser.

No, there is no way to explicitly destruct an object.

This article has been dead for over six months. Start a new discussion instead.