Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out how long an Ajax request took to complete

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;     } } 
like image 917
Chris Dutrow Avatar asked Aug 17 '10 00:08

Chris Dutrow


People also ask

How do you know AJAX request has been completed?

By determining the readyState property value of XMLHttpReqyest, One can know if the request is completed. If the readyState value = 4, the request has been completed and the data is available.

How do I get AJAX response time?

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(); $.

Why does AJAX take so much time?

If this is a busy server or overloaded server, then it could be that your app is swapped out of memory or the cache is empty and it takes a longer time to get your app up and running and ready to start processing the response.

Are AJAX calls slow?

In sites that rely upon Ajax for functionality (or even pizzazz), performance becomes even more critical than the general JavaScript performance. Because Ajax requests take place behind the scenes, to the end user there is little discernible difference between an Ajax request being slow, and nothing happening at all.


2 Answers

This is the proper way to do it.

$.ajax({     url: 'http://google.com',     method: 'GET',     start_time: new Date().getTime(),     complete: function(data) {         alert('This request took '+(new Date().getTime() - this.start_time)+' ms');     } }); 

https://jsfiddle.net/0fh1cfnv/1/

like image 30
Anonymous Avatar answered Oct 08 '22 13:10

Anonymous


@codemeit is right. His solution looks something like the following using jQuery for the ajax request. This returns the request time in milliseconds.

var start_time = new Date().getTime();  jQuery.get('your-url', data, function(data, status, xhr) {         var request_time = new Date().getTime() - start_time; }); 
like image 180
Isaac Avatar answered Oct 08 '22 13:10

Isaac