시계

시간을 매초 갱신하면서 출력하는 시계

index.html
<!DOCTYPE html> 
<html>
<head>
    <title>My First Web Clock!</title>
    <link rel="stylesheet" href="index.css" />
</head>
<body>
    <h1>매초 시간이 갱신되어 출력</h1>
    <div class="js-clock">
    <h1>00:00</h1>
    </div>
    <script src="clock.js"></script>
</body>

</html>
clock.js
const clockContainer = document.querySelector(".js-clock"),
    clockTitle = clockContainer.querySelector("h1");

function getTime(){
    const date = new Date();
    const minutes = date.getMinutes();
    const hours = date.getHours();
    const seconds = date.getSeconds();
    clockTitle.innerText = `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
}

function init(){
    getTime();
    setInterval(getTime, 1000);
}

init();
/*만약 hours의 값이 10 미만이라면
(1,2,3,...9)앞에 0을 붙여서 hours값을 반환하고
그렇지 않으면 날것의 hours를 반환하라 
*/

${hours < 10 ? `0${hours}` : hours}

Last updated