Let’s take a look at the code:
//Calculate the difference in milliseconds.
var time = performance.now() - this.startTime;
//Convert milliseconds to seconds.
var seconds = time / 1000;
//Round to 3 decimal places.
seconds = seconds.toFixed(3);
//Write the result to the HTML document.
var result = 'AJAX request took ' + seconds + ' seconds to complete.';
document.body.innerHTML = result;
//Or log it to the console.
- We created a custom property called startTime, which we assigned the return value of performance.now() to.
- The performance.now() method returns the number of milliseconds that have occurred since the document’s creation (also known as the “time origin”).
- Inside the success function, we calculated the difference between the startTime timestamp and the current timestamp. In short, we calculated how many milliseconds passed between the start of the request and the end of the request.
- Afterwards, we converted the difference into seconds and outputted the result in a more human-friendly format.
If you run the example above, you will see that the code outputs the number of seconds that it took for the AJAX request to successfully complete.
Hopefully, you found this code to be useful!