Skip to content Skip to sidebar Skip to footer

Getting AJAX Request Duration

I would like to get the duration for a certain ajax request using jquery. For instance I am using this script: $.ajax({ type: 'GET', url: 'http://localhost/thescript.php', su

Solution 1:

You can use the beforeSend() and complete() functions to compare the current timestamps and calculate the difference.

http://api.jquery.com/jQuery.ajax/

Here you can see all callback hooks provided by $.ajax: http://api.jquery.com/jQuery.ajax/#callback-functions


Solution 2:

How 'bout:

var start = new Date().getTime();
$.ajax({
  type: "GET",
  url: "http://localhost/thescript.php",
  success: function(data){
    $("#container").html(data);
  },
  complete: function(jqXHR, textStatus){
    var duration = (new Date().getTime() - start) / 1000;
    alert("http://localhost/thescript.php took '" + duration + "' second(s) to load");
  }
});

Solution 3:

something like this:

var start_ts;
$.ajax({
 type: "GET",
 url: "http://localhost/thescript.php",
 beforeSend: function() {
   start_ts = new Date().getTime();
 }
 success: function(data){
  $("#container").html(data);
 },
 complete: function(jqXHR, textStatus){
  var end_ts = new Date().getTime();
  var dif = (end_ts - start_ts) / 1000; /* convert milisec to sec */
  alert("http://localhost/thescript.php took '"+dif+"' seconds to load");
 }
});

Post a Comment for "Getting AJAX Request Duration"