Displaying Dynamic Elapsed Time in JavaScript

Image for post
Image for post
Photo by Aron Visuals on Unsplash

1) Implement a function to compute the elapsed time

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).
// Record end timelet endTime = new Date();
// Compute time difference in millisecondslet timeDiff = endTime.getTime() - startTime.getTime();
// Convert time difference from milliseconds to secondstimeDiff = timeDiff / 1000;

1 .1. Extract Seconds

// 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

// Convert time difference from seconds to minutes using %timeDiff = Math.floor(timeDiff / 60);
// 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

// Convert time difference from minutes to hourstimeDiff = Math.floor(timeDiff / 60);
// Extract integer hours that don't form a day using %let hours = timeDiff % 24;
// Convert time difference from hours to daystimeDiff = Math.floor(timeDiff / 24);// The rest of timeDiff is number of dayslet days = timeDiff;
// 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

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

2) Display Elapsed Time & Update it Dynamically

// Define the initial value for the displayed string
var displayedElapsedTime = "00:00";
// Defines a start date for elapsed time
var startDate = new Date();
// Set up a timer that recomputes the elapsed time every secondvar elapsedTimeIntervalRef = setInterval(() => {displayedElapsedTime = timeAndDateHandling.getElapsedTime(startDate);}, 1000); // 1000 as in 1 second
clearInterval(elapsedTimeIntervalRef);

Stopwatch Code Demo

Developer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store