JS 5강

이효원·2023년 5월 10일

노마드스터디

목록 보기
4/16
post-thumbnail

5강에서는 시계를 만든다. 시계를 만들기 위해서 clock.js라는 새로운 파일을 만들어주고 HTML에서도 h2태그를 새로 만들어준다. 00:00부터 시작하므로 h2태그에 작성해준다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Momentum</title>
</head>
<body>
    <form class="hidden" id="login-form">
        <input 
            required
            maxlength="15" 
            type="text" 
            placeholder="What is your name"/>
        <button>Log In</button>
    </form>
    <h1 id="greeting" class="hidden"></h1>
    <h2 id="clock">00:00</h2>
    <script src="clock.js"></script>
</body>
</html>

아래는 clock.js코드이다.

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.innerText = `${hours}:${minutes}:${seconds}`;
}
getClock()
setInterval(getClock,1000);

위 코드에서 get은 1씩 가져다 주는 역할을 한다.그래서 getHours는 1시간씩 늘어나고 getMinutes는 1분씩, getSeconds는 1초씩 가져다주는 역할이다. 여기서 한자리수일 때 보기 안좋기 때문에 앞에 0을 붙여서 00:00과 자릿수를 맞춰줘야 하는데, 이것을 해주는 것이 padStart이다. 2,"0"은 2칸씩 "0"을 붙여준다는 뜻이다.
여기서 만든 getClock함수를 아래에서 setInterval해주는데, 이것은 1초에 한번씩 이 시계 함수를 불러와준다.그래서 계속 시간이 바뀔 수 있는 것이다.

0개의 댓글