Displaying Dynamic Elapsed Time in JavaScript

Reema Alzohairi
7 min readJul 11, 2020
Photo by Aron Visuals on Unsplash

As a front-end developer, you may come across several use cases where you need to display the elapsed time dynamically. For example, you may need to display the elapsed time in a call interface or you may want to develop a stopwatch feature in your website. Therefore, having a reliable function that you can simply revisit and reuse would be, to simply put it, a life saver. So, I’m here to save your life.

In this post, I’m going to explain how the elapsed time can be computed and displayed using JavaScript. However, the same algorithm and logic can be applied to whatever programming language you are using.

1) Implement a function to compute the elapsed time

The first building block is to implement a function that computes the elapsed time between a starting date and an end date, where the end date is the time captured the moment the function is invoked.

To achieve this, the function getElapsedTime() will be implemented with the following description.

Note: The solution was implemented with reference to the solution found here.

getElapsedTime() — Returns the elapsed time in the format mm:ss or hh:mm:ssInput: a date, representing the start time.Output: the passed time in the format mm:ss or hh:mm:ss (if hours is defined).

Once the function starts, the end time will be recorded, which is the time of function execution. This is demonstrated by the following code.

// Record end timelet endTime = new Date();

After that, the time difference between the start time and end time will be computed. This will be done by converting both dates to their total milliseconds equivalent and then subtracting the start time in milliseconds from the end time in milliseconds as shown in the following code.

// Compute time difference in millisecondslet timeDiff = endTime.getTime() - startTime.getTime();

Note: the getTime() built-in date function returns the elapsed time between Jan 1st, 1970 00:00:00 UTC and the given date. Therefore, subtraction will always be correct as getTime()