Calculating the execution time of an AJAX request.

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:

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.

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!

Facebook Comments