Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How long does my AJAX call take?

I want to do something like

var date = new Date();
var pretime = date.getTime();

$.post(    
    "ajaxfile.php", 
    object, 
    function(data) {
        var totalTime = date.getTime()-pretime;
        $("#feed").append("Time: " + totalTime + "<br/>" + pretime + "<br/>" + date.getTime() + "<br/>");
    });
});

That is, measure how long the AJAXcall lasts before I get a response. But the print from this callback function is:

Time: 0
1326184886814
1326184886814

What is the solution to this?

like image 628
Gustav Avatar asked Jan 20 '26 23:01

Gustav


2 Answers

getTime() is returning the same value because you are reusing the same Date() object. You need to create a new Date object:

var date = new Date();
var pretime = date.getTime();
        $.post("ajaxfile.php", object, function(data){
            var date2 = new Date();
            var totalTime = date2.getTime()-pretime;
            $("#feed").append("Time: " + totalTime + "<br/>" + pretime + "<br/>" + date.getTime() + "<br/>");
        });
});
like image 168
ctcherry Avatar answered Jan 22 '26 12:01

ctcherry


I'm no Javascript expert, but it seems to me that you're creating a single Date object which (if it's similar to Java's Date object) stores the date/time at the point it was created, and then using that same date object twice - i.e. comparing the start date/time to itself.

Try creating a second Date object inside the AJAX callback function to capture the end time.

like image 29
dty Avatar answered Jan 22 '26 12:01

dty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!