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() function always computes from a unified starting point.

When the time difference in milliseconds is obtained, it’s time to convert it from milliseconds to seconds, so that we can start extracting the seconds, the minutes, the hours and the days from it. This is done by dividing the time difference by 1000 as shown in the following code.

// Convert time difference from milliseconds to secondstimeDiff = timeDiff / 1000;

1 .1. Extract Seconds

To extract the seconds, we will be needing to consider only the seconds that never got to form a full minute. Meaning, the remainder of timeDiff after dividing it by 60.

Once the correct value of seconds is obtained, the ⌊floor⌋ function is applied to extract only integer seconds and ignore the possible leftover incomplete second, if any. After that, seconds will be converted to a string and get padded with zero as a prefix if it’s a single digit. Seconds extraction is demonstrated in the following code.

// Extract integer seconds that do not form a minute using %let seconds = Math.floor(timeDiff % 60);// Pad seconds with a zero (if necessary) and convert to stringlet secondsAsString = seconds < 10 ? "0" + seconds : seconds;

1 .2. Extract Minutes

To get ready to extract the minutes, the time difference needs to be converted from seconds to minutes first. This is done by dividing the timeDiff by 60 and then applying the floor function to the obtained value as shown in the following code.

Note: the ⌊floor⌋ function is applied at this point as we no longer care about incomplete minutes as they have already been handled as seconds.

// Convert time difference from seconds to minutes using %timeDiff = Math.floor(timeDiff / 60);

To extract the minutes, just like extracting the seconds, we will be needing to consider only the minutes that didn’t get to be a part of a full hour. Meaning, the remainder of timeDiff after dividing it by 60.

After that, the minutes is converted to a string and padded with zero if necessary as shown in the following code.

Note: the ⌊floor⌋ function is not needed here as incomplete minutes were already handled as seconds in the previous steps.

// Extract integer minutes that don't form an hour using %let minutes = timeDiff % 60;// Pad minutes with a zero (if necessary) and convert to stringlet minutesAsString = minutes < 10 ? "0" + minutes : minutes;

1 .3. Extract Hours

To get ready to extract the hours, the time difference needs to be converted from minutes to seconds first. This is done by dividing the timeDiff by 60 and then applying the floor function to the obtained value as shown in the following code.

Note: the ⌊floor⌋ function is applied at this point as we no longer care about incomplete hours as they have already been handled as minutes.

// Convert time difference from minutes to hourstimeDiff = Math.floor(timeDiff / 60);

To extract the hours, just like extracting the minutes & seconds, we will be needing to consider only the hours that didn’t get to be a part of a full day (full 24 hours). Meaning, the remainder of timeDiff after dividing it by 24.

Note: the ⌊floor⌋ function is not needed here as incomplete hours were already handled as minutes in the previous steps.

// Extract integer hours that don't form a day using %let hours = timeDiff % 24;

At this point we have extracted the hours the do not represent a full day. The next step is to convert all the days in the elapsed time to hours and add it to the hours variable to have the full accurate count of hours.

To extract the days, the time difference needs to be converted from hours to days. This is done by dividing the timeDiff by 24 and then applying the floor function to the obtained value as shown in the following code. At this point, timeDiff equals the number of days.

Note: the ⌊floor⌋ function is applied at this point as we no longer care about incomplete days as they have already been handled as hours.

// Convert time difference from hours to daystimeDiff = Math.floor(timeDiff / 24);// The rest of timeDiff is number of dayslet days = timeDiff;

Now to compute the total number of hours, we convert the number of days to hours and add it to the hours variable. To convert the number of days to hours, we simply multiply the number of days by the number of hours in a day (24).

After that, the hours is converted to a string and padded with zero, if necessary, as shown in the following code.

// The rest of timeDiff is number of dayslet days = timeDiff;let totalHours = hours + (days * 24); // add days to hourslet totalHoursAsString = totalHours < 10 ? "0" + totalHours : totalHours;

1.4. Format and Return the Elapsed Time

Now that we have the full elapsed time computed, it’s time to format it appropriately and return the value. Easy-peasy.

As shown in the following code, the elapsed time will be formatted as mm:ss, if the amount of hours calculated is zero. Otherwise, the format hh:mm:ss will be returned.

At this point, feel free to format the elapsed time whichever way you like.

if (totalHoursAsString === "00") {return minutesAsString + ":" + secondsAsString;} else {return totalHoursAsString + ":" + minutesAsString + ":" + secondsAsString;}

2) Display Elapsed Time & Update it Dynamically

At this point, we have the functionality of computing the elapsed time implemented, which is great. Now, it’s time to display the elapsed time and update it every passing second.

To achieve this, first we need to define a variable that will be holding the string value of the elapsed time. This variable will be initialized with the value "00:00", which represents the initial elapsed time and will be updated to reflect the elapsed time every second.

This variable is going to be the value of the innerText property of whatever HTML element you decide to be holding the elapsed time value for you. This is demonstrated by the following code.

// Define the initial value for the displayed string
var displayedElapsedTime = "00:00";

Next, you need to define a start date, which is going to be passed to getElapsedTime() as a starting point of the computation every passing second. This is demonstrated by the following code.

// Defines a start date for elapsed time
var startDate = new Date();

Now that we have the variables ready, it’s time to set up an interval using JavaScript’s setInterval function. This function will execute the passed callback every second until the interval is manually cleared.

The passed callback will update the elapsed time by triggering a re-computation of the elapsed time using the getElapsedTime function and passing the startDate variable.

This is demonstrated by the following code.

// Set up a timer that recomputes the elapsed time every secondvar elapsedTimeIntervalRef = setInterval(() => {displayedElapsedTime = timeAndDateHandling.getElapsedTime(startDate);}, 1000); // 1000 as in 1 second

Note: make sure to save the reference of this interval, which is the value returned from setInterval, to be able to stop it when desired. This is demonstrated by the following code.

clearInterval(elapsedTimeIntervalRef);

Stopwatch Code Demo

This code demo demonstrates a Stopwatch feature implemented using the explained methodology for displaying the dynamic elapsed time using JavaScript.

You can also clone the source code from my Github. To access the Stopwatch code demo in JavaScript, click the following link.

To access the Stopwatch demo in TypeScript (Angular framework), click the following link.

--

--

Responses (2)