14

I want to measure how long it takes to process AJAX call. I have it up and running but don't know how to code this in javascript (js only)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Radek
  • 13,813
  • 52
  • 161
  • 255

2 Answers2

28
var start = new Date().getTime();
doAjax({
  success: function() {
    var end = new Date().getTime();
    console.log('milliseconds passed', end - start);
  }
});

save a time value before you start doing ajax stuff, and then do it again when it finishes. Then subtract one form the other and get your time.

George Reith
  • 13,132
  • 18
  • 79
  • 148
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • @Alex, any ideas on why would this be different from the one in Firebug by 30-60 ms? Thanks – Adi Jul 31 '12 at 15:53
  • Probably because whatever ajax library you are using (like jQuery) runs code after the response is received, but before the callback is executed. Firebug is likely measuring only the HTTP timing. The discrepancy is likely just library overhead. – Alex Wayne Jul 31 '12 at 19:32
3

This will not give accurate timings because javascript uses an event queue. That means your program may execute like this:

  • Start AJAX request
  • Handle a waiting mouse click event / any other waiting line of code in the meantime
  • Start handling the AJAX ready response

Unfortunately there is no way to get the time the event was added to the queue as far as I know. Event.timeStamp returns the time the event was popped from the queue, see this fiddle: http://jsfiddle.net/mSg55/.

Html:

<a href="#">link</a>
<div></div>

Javascript:

$(function() {
    var startTime = new Date();
    $('a').click(function(e) {
        var endTime = new Date(e.timeStamp);
        $('div').append((endTime - startTime) + " ");
        //produce some heavy load to block other waiting events
        var q = Math.PI;
        for(var j=0; j<1000000; j++)
        {
            q *= Math.acos(j);
        }
    });

    //fire some events 'simultaneously'
    for(var i=0; i<10; i++) {
        $('a').click();
    }
});
Community
  • 1
  • 1
Aristoteles
  • 708
  • 2
  • 7
  • 15