Find out how long an Ajax request took to complete

Viewed 63582

What is a good way to find out how long a particular $.ajax() request took?

I would like to get this information and then display it on the page somewhere.

ANSWER??::::

I'm new to javascript, this is the best that I could come up with if you don't want to inline the "success" function (because it will be a much bigger function) Is this even a good way to do this? I feel like I'm over complicating things...:

makeRequest = function(){
    // Set start time
    var start_time = new Date().getTime();

    $.ajax({ 
        async : true,
        success : getRquestSuccessFunction(start_time),
    });
}

getRquestSuccessFunction = function(start_time){
    return function(data, textStatus, request){
        var request_time = new Date().getTime() - start_time;
    }
}
9 Answers

How About This:

First Globally Set the property TimeStarted with the request object.

$(document).ajaxSend(function (event, jqxhr, settings) {
    jqxhr.TimeStarted = new Date();
});

And then call any ajax

var request = $.ajax({ 
    async : true,
    success : function(){
    alert(request.TimeStarted);
   },
});

I fiddled a bit and got a generic function that can be displayed for all ajax calls. This means that you don't have to do the same thing for every single ajax call

var start_time;   
$.ajaxSetup({
  beforeSend: function () {
    start_time = new Date().getTime();
  },
  complete: function () {
    var request_time = new Date().getTime() - start_time;
    console.log("ajax call duration: " + request_time);
  }
});

You may use the below code spinet.....

var d1 = new Date();  
$.ajax({
    type: 'GET',
    contentType: "application/json; charset=utf-8",
    url: '/Survey/GET_GetTransactionTypeList',
    data: {},
    dataType: 'json',
    async: false,
    success: function (result) {
        var d2 = new Date();
        var seconds = (d2 - d1) / 1000;
        console.log(seconds);           
    },
    error: function (request, status, error) {
        alert(request.statusText + "/" + request.statusText + "/" + error);
    }
}); 

If you want to reduce ajax call init duration, just set async value as false instead of true. Like this ways....

async: false,
Related