21

So I am working on tool that can show long a request to a page is taking.

I am doing this by using jQuery Ajax (http://api.jquery.com/jQuery.ajax/) and I want to figure out the best way to get the response time.

I found a thread (http://forum.jquery.com/topic/jquery-get-time-of-ajax-post) which describes using the "Date" in JavaScript, but is this method really reliable?

An example of my code could be this below

$.ajax({
    type: "POST",
    url: "some.php",
}).done(function () {
    // Here I want to get the how long it took to load some.php and use it further
});
Dumpen
  • 1,622
  • 5
  • 25
  • 35

1 Answers1

46

The most simple method would be to add var ajaxTime= new Date().getTime(); before the Ajax call and in the done get the current time to calculate how long the Ajax call took to make.

var ajaxTime= new Date().getTime();
$.ajax({
    type: "POST",
    url: "some.php",
}).done(function () {
    var totalTime = new Date().getTime()-ajaxTime;
    // Here I want to get the how long it took to load some.php and use it further
});

Or in case of you want to know how long time this take on the server side. Do the same and print the time in the return value from some.php.

ivandov
  • 519
  • 6
  • 13
FIG-GHD742
  • 2,446
  • 1
  • 17
  • 26
  • 13
    You can use `Date.now()` instead of the longer `new Date().getTime()`. It doesn't only save characters but also saves creation of a `Date` object. – Daniel Böhmer Jul 17 '13 at 19:09
  • 2
    @DanielBöhmer Regarding `Date.now()` - it's not available in some older browsers (e.g. IE8), you might need a polyfill, see [MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/now) – Adam Chwedyk Jun 01 '15 at 18:52
  • 1
    downvoting - won't work for multiple requests – Anonymous Mar 11 '17 at 02:27