Doug Molineux
Doug Molineux

Reputation: 12431

Figure out how much time it takes to do an AJAX request

I am attempting to figure how long it takes to do an AJAX request, when a button is clicked so far I have this code:

$(document).ready(function() {
    $('#start').click(function() {
        start_timer();
        var record = $.ajax({url: "ajax.php?getSensor="+devid, async: false }).responseText;
        $("textarea#recordTextbox").val($('textarea#recordTextbox').val()+record+"\n");
        stoptimer();
    }); 
});

And my timer functions look like this:

function start_timer() {
     display();
}
function stoptimer() {
  clearTimeout(timer);
  timer = 0;
}
function display(){
  if (millisec>=9){
     millisec=0
     seconds+=1
  }
  else
     millisec+=1
     $("#time").html(seconds + "." + millisec);
     timer = setTimeout("display()",100);
  }

The AJAX request is sent properly but the timer reads 0.1 seconds everytime, I know that it takes longer than this because the page hangs for at least 3 seconds. For some reason the timer does not run when its off doing its AJAX deal.

Any advice would help, thanks!

Upvotes: 0

Views: 349

Answers (4)

Gary
Gary

Reputation: 7257

Just run YSlow over it.

For a general purpose approach to determining what's wrong with your page loads and AJAX requests, then use the YSlow addon for Firefox.

It'll show you stuff that you've never even dreamed of that's slowing your code down.

Upvotes: 0

Doug Molineux
Doug Molineux

Reputation: 12431

I couldn't get this timer to work, so I used Date().getTime() like this:

    var start_time = new Date().getTime();       
    $.ajax({url: "ajax.php?getSensor="+devid, async: false, success: function(data){ 
        $("textarea#recordTextbox").val($('textarea#recordTextbox').val()+data+"\n");
        request_time = new Date().getTime() - start_time; 
    }});
    $("#time").html(request_time/1000);

Upvotes: 1

Byron Whitlock
Byron Whitlock

Reputation: 53921

If you are doing this to aid development, use firebug.

Upvotes: 1

Dmitri Farkov
Dmitri Farkov

Reputation: 9691

You can do this easier with an asynchronous request as such:

$(document).ready(function() {
    $('#start').click(function() {
        start_timer();
        $.ajax({url: "ajax.php?getSensor="+devid, async: false, success: function(data){ 
            $("textarea#recordTextbox").val($('textarea#recordTextbox').val()+data+"\n");
            stoptimer(); 
        }});
    }); 
});

Upvotes: 3

Related Questions