d-_-b
d-_-b

Reputation: 23181

measuring ajax load time

I have an $.ajax request and am saving the start time, and end time (using new Date().getMilliseconds()). I see a weird occurrence where sometimes I subtract startTime from endTime and get a negative number.

(function(){
    var startTime = new Date().getMilliseconds();
    $.ajax({
        url:"/url.php",
        data: someObject,
        method: "POST",
        complete:function(r){
            var endTime = new Date().getMilliseconds();
            console.log(endTime - startTime); // sometimes negative?!
        }
    });
})();

Could someone please explain this? I'm sure there's a logical explanation aside from a rip in the space-time continuum.

(If there's a better way to measure this, that'd be appreciated too!)

Upvotes: 5

Views: 4938

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

A little test says:

var date     = new Date();
var systemMS = date.getMilliseconds();
var timeMS   = date.getTime();


alert( 'Currently your clock is at ms :   '+ systemMS );
alert( '"ms" since 1 January, 1970 UTC. : '+ timeMS   );

So try with:

var start = new Date().getTime(); // note getTime()
$.ajax({
    url     :"/url.php",
    data    : someObject,
    method  : "POST",
    cache   : false,              // prevent caching response
    complete: function(){
        var end = new Date().getTime();
        console.log( end - start );
    }
});

MDN says:

getMilliseconds The value returned by getMilliseconds is a number between 0 and 999.

Upvotes: 3

Cameron Askew
Cameron Askew

Reputation: 1413

This will often be negative (about half the time), as this is not getting the number of milliseconds since the epoch (1/1/1970). This is rather getting the number of milliseconds of the current date time. So if 400 milliseconds have passed since the last second, you will get 400...if 800 milliseconds have passed since the last second, you will get 800.

The function you are looking for is: new Date().getTime()

Upvotes: 5

user2625787
user2625787

Reputation:

.getMilliseconds returns the milliseconds portion of the time when you created the Date object. So in 50% of your comparisons the portion will be higher or lower than that of any other Date object.

What you want is new Date().getTime(), which returns absolute milliseconds since the Unix epoch began in 1970.

Upvotes: 8

Related Questions