1

I'm loading a .txt file located on my server with this simple method:

function getFileFromServer(url, doneCallback) 
{
 console.time("getFileFromServer");
 var xhr;

 xhr = new XMLHttpRequest();
 xhr.onreadystatechange = handleStateChange;
 xhr.open("GET", url, true);
 xhr.send();

 function handleStateChange() {
     if (xhr.readyState === 4) {
         doneCallback(xhr.status == 200 ? xhr.responseText : null);
     }
 }
 console.timeEnd("getFileFromServer");
}

I'm using it in this simple way, accordingly to this post: Reading a txt file from Server, writing it to website

function loadFile( url ) {
    console.time("loadFile");
    getFileFromServer(url, function(text) {
    if (text === null) {
        console.log("error-loading-file");
    }
    else {
        console.timeEnd("loadFile");
        doStuff(text);
    }
});

As you can see I've put the console.time to keep track of the timing. Here's what the browser console answer:

getFileFromServer: 1.744ms

loadFile: 18114.871ms

I'm not a javascript expert, and the only thing I can figure out to explain the timing difference is the argument passing(value vs reference in C++). Someone can explain me this difference in timing?

Community
  • 1
  • 1
bartux
  • 111
  • 5
  • this is because of the `async` nature of the ajax calls. http://stackoverflow.com/questions/11233633/understanding-asynchronous-code-in-laymans-terms – shakib Aug 24 '16 at 08:33

1 Answers1

1

The reason why getFileFromServer finishes very fast is that there is no real processing done. The function does not wait until the request returns from the server but only registers the callback function for when it does. That means it took 1.744ms to send the request, nothing more.

The loadFile function is measuring the time between sending the request and actually getting a response. That is the difference.

lcs.bdr
  • 388
  • 1
  • 9