Reputation: 32848
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.
Upvotes: 2
Views: 144
Reputation: 145162
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 always
handler first. Since Deferred
callbacks are executed in the order they are added, binding always
first means we won't have the measurement thrown off by computationally expensive operations in the done
handler.
There's no need to instatiate Date
objects. The static Date.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
/fail
callbacks.
function aa() {
var start = Date.now(), elapsed;
$.ajax({
cache: false,
url: href + params.param,
dataType: 'html'
})
.always(function () {
elapsed = Date.now() - start;
});
.done(function (responseText) {
xx(elapsed);
})
.fail(function (jqXHR, textStatus, errorThrown) {
yy(elapsed);
});
};
Upvotes: 1
Reputation: 2861
If you are using Ruby or .Net, you can take a look to MiniProfiler. It will do what you want. Or maybe you can take check how he is doing it inside.
Upvotes: 0
Reputation: 23873
Perhaps run some kind of monitoring PC that just reloads the page every once in a while and keeps its own log ... sending out an alert if the transfer takes too long.
Under *nix, you could automate that with a simple script and wget and/or curl.
Upvotes: 0
Reputation: 354
I would argue that your way is pretty clean. There is nothing built-in to the response that tells you how long a request takes unless you put it there yourself. If you try to do some sort of server-side logging though, that will not take into account the time taken for the request to get across the wire.
Upvotes: 0