Making a clock with " setInterval " and padStart
Seongjin Park
1 min read
to make a clock with javascript
I used
new Date() object
which returns me " Tue Aug 15 2023 00:00:51 GMT+0900 " this information.
and used method
getHours(), getMinutes(), getSeconds() to get each elements.
const clock = document.querySelector("h2#clock");
function getClock() {
const date = new Date();
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
clock.innerHTML = `${hours}:${minutes}:${seconds}`;
}
getClock();
setInterval(getClock, 1000);
and for the end, I used setInterval to make it sure this function happens every single second.
#padStart
to show time as digital clock (ex. 00:00:00 )
I used padStart(2, "0").
"1".padStart(2, "0"); -> "01"
0
Subscribe to my newsletter
Read articles from Seongjin Park directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by