简体   繁体   中英

measure processing time of AJAX call

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)

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.

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();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM