+ 1

Easier way to manipulate the html paragraph

So I have a timer variable, and this variable points to a paragraph in html. The code is time.innerHTML = hr + ":" + min; Note: hr and min are variables that store the current time. So, in order to avoid a situation where the time shows as "9:7" when it's 09:07am, I added a bunch of if statements If(hr < 10){ timer.innerHTML = "0" + hr + ":" + min; } If (min < 10){ timer.innerHTML = hr + ":" + min; } However, I want to do so for hours, minutes, and seconds aswell. Is there a more efficient way to do this rather than with a bunch of if statements. Because it might become quite tedious to write if statements for every possiblity.

4th Aug 2022, 6:02 PM
Robby kangwa
Robby kangwa - avatar
2 Answers
+ 3
Otherwise you could use a utility function. function leftPad(time) { return time <10 ? "0" + time : time} And then e.g timer.innerHTML = [hr,min,sec].map(leftPad).join(":")
4th Aug 2022, 7:11 PM
John Doe
4th Aug 2022, 7:07 PM
John Doe