I am trying to measure the time an asynchronous http request is processed by an http server developed in nodejs. By that I mean the time from which the server informs the client starting to process the request, to the time the server finishes processing and returns the response back to the client.
So, accrding to XMLHttpRequest documentation for readyState I am under the impression that the time difference between when readyState == 3 to readyState == 4 gets me what I want. In practice I get almost 0 to be the time difference between the two. However my expectation, according to the code snippets below is to get something around to 2000+ ms.
Why is that and how can I roughly measure the processing time in practice?
Client side:
<script>
let begin;
const xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://mydomain. com/API", true);
xhttp.send();
xhttp.onreadystatechange = function () {
if (this.readyState == 3) {
begin = Date.now();
}
if (this.readyState == 4 && this.status == 200) {
console.log("Execution time (ms):" + (Date.now() - begin));
}
};
</script>
server side ( as seen, processing a request takes around 2000ms)
let http = require('http');
let url = require('url');
let server = http.createServer(function (req, res) {
reqReceived++;
let q = url.parse(req.url, true);
res.writeHead(200, {
"Content-Type": "text/html",
"Access-Control-Allow-Origin": "*"
});
setTimeout(() => {
res.end(`response is ready`);
}, 2000);
});
server.listen();
You might argue that I should have put writing the head inside the timeout callback, however it would not still make any time difference for the client to receive readyState ==3 and == 4.