This is a short JavaScript tutorial on how to calculate the execution time of an AJAX request. This can be useful if you need to know how long an AJAX request took to complete. In this example, I will be using the JQuery library.
Let’s take a look at the code:
$.ajax({ url: 'http://localhost/', startTime: performance.now(), success: function(){ //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. console.log(result); } });
In the JavaScript above, we created a very simple AJAX GET request. A few things to note here:
- 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 by rounding the decimal places.
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!