0

Possible Duplicate:
How to get progress from XMLHttpRequest

totalI am trying to download a 1 mb file with xmlhttprequest and check the download time for bandwidth measurement. However following codes give me just response time from server. It doesn't wait until all file loaded.

var start = new Date().getTime();
(function rec() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', "https://www.example.com/test/dummyFile1024kb", true);   
xmlHttp.setRequestHeader("Cache-Control", "no-cache");
xmlHttp.onreadystatechange = function () {
     if (xmlHttp.readyState == 4) {
         var total=(new Date() - start)            
         alert(total)    
        };
       xmlHttp.send(null);
    })();

What should I do in order to download all file? Any other suggestions are welcome.

Community
  • 1
  • 1
user1874941
  • 3,013
  • 4
  • 20
  • 31
  • @leepowers - nope. OP isn't asking for intermediate progress events, just why his time calculation isn't working when the request appears to be complete. – broofa Jan 12 '13 at 02:01
  • What do `xmlHttp.status` and `xmlHttp.responseText.length` show when your alert fires? I've never seen readyState=4 before a response is fully loaded unless there's some sort of error or the request gets interrupted. – broofa Jan 14 '13 at 17:20

1 Answers1

1

xmlHttp.send(null); should not be inside your onreadystatechange function, but should be after it. Calling send() on an in-progress XHR request will result in unspecified behavior, if not outright errors. And the fact it's inside your readystatechange handler implies you have some other code that's not shown that's calling xmlHttp.send(), otherwise that handler would never get called (and your alert would never fire).

I.e. I think what you want is:

(function rec() {
  var start = new Date().getTime();
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open('GET', "https://www.example.com/test/dummyFile1024kb", true);   
  xmlHttp.setRequestHeader("Cache-Control", "no-cache");
  xmlHttp.onreadystatechange = function () {
   if (xmlHttp.readyState == 4) {
      var total=(new Date() - start)            
      alert(total)    
    };
  };
  xmlHttp.send(null);
})();
broofa
  • 37,461
  • 11
  • 73
  • 73