Created
December 11, 2022 12:48
-
-
Save dougmartin/6ebc8d7a3c03156b8de73720eae51f37 to your computer and use it in GitHub Desktop.
Given a elapsed time in milliseconds and an optional precision returns a formatted string in the form of Xh Ym Zs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
example: | |
const startTime = Date.now(); | |
... some long computation ... | |
const elapsedInMS = Date.now() - startTime; | |
console.log(formattedElapsedTime(elapsedInMS, 3)); | |
*/ | |
const formattedElapsedTime = (elapsedInMS, precision) => { | |
precision = precision || 2; | |
const secondsInMS = 1000; | |
const minutesInMS = secondsInMS * 60; | |
const hoursInMS = minutesInMS * 60; | |
let remainingInMS = elapsedInMS; | |
const hours = Math.floor(remainingInMS / hoursInMS); | |
remainingInMS -= (hours * hoursInMS) | |
const minutes = Math.floor(remainingInMS / minutesInMS); | |
remainingInMS -= (minutes * minutesInMS) | |
const seconds = remainingInMS / secondsInMS; | |
const result = []; | |
if (hours > 0) { | |
result.push(`${hours.toFixed(precision)}h`); | |
} | |
if (minutes > 0) { | |
result.push(`${minutes.toFixed(precision)}m`); | |
} | |
result.push(`${seconds.toFixed(precision)}s`); | |
return result.join(" "); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment