I am looking at a method like this:
function aa() {
var start = new Date().getTime();
$.ajax({
cache: false,
url: href + params.param,
dataType: 'html'
})
.done(function (responseText) {
xx();
})
.fail(function (jqXHR, textStatus, errorThrown) {
yy();
})
.always(function () {
zz(start);
});
};
function zz(start) {
var end = new Date().getTime();
var elapsed = end.getMilliseconds() - start.getMilliseconds();
}
First of all. Is this a valid way to measure the time it takes? Also is there another way that I could do this. For example is there some way I could read something from the Ajax header and if so how could I read it?
Please note I am looking for a solution in code so I can report the times on an HTML page.
This is absolutely a valid way to measure the amount of time between when a request is issued and when data is returned. The goal is to measure the amount of time the client sees pass between issuing a request and receiving a response, so using the client’s clock is ideal. (You usually want to avoid time comparisons that involve syncing the server’s and client’s clocks; using the
Date:HTTP header would do just that.)There are two things I would do to improve:
Bind the
alwayshandler first. SinceDeferredcallbacks are executed in the order they are added, bindingalwaysfirst means we won’t have the measurement thrown off by computationally expensive operations in thedonehandler.There’s no need to instatiate
Dateobjects. The staticDate.now()returns the current time in ms as a Number.You could even do the elapsed calculation in scope so it’s available to your
done/failcallbacks.