챕터 3개밖에 안남은 노마드 코더 ! 오늘은 시계 나타내기를 진행했다.
Date클래스를 사용해서 현재시각을 가져오는데 화면에 시간이 계속 바뀌는 걸 나타내려면 interval함수를 사용하면 되는 것과 반복이 아니라 시간을 정해서 한번 출력 하고싶으면 timeout함수를 사용하면 된다.
html에 먼저 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="css/style.css" />
<title>Momentum</title>
</head>
<body>
<form id="login-form" class="hidden">
<input type="text" placeholder="What is your name?">
<input type="submit" value="Log In">
</form>
<h2 id="clock">00:00</h2>
<h1 id="greeting" class="hidden"></h1>
<script src="js/greetings.js"></script>
<script src="js/clock.js"></script>
</body>
</html>
기본적인 문구는 00:00으로 지정해주고 자바스크립트에서 값을 넣어주자.
Date클래스는 오늘 날짜와 시간을 나타낸다.
그리고 다양한 함수를 가지고 있는데 시간을 나타내기 위해 getHours(), getMinutes(), getSeconds()함수를 사용해주자.
const date = new Date();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
clock.innerText=`${hours}:${minutes}:${seconds}`;
현재 시각이 나오지만 한자리 숫자일 때는 "0"이 붙게 해주기 위해 숫자를 문자타입으로 받아주는 String으로 형변환 후 padStart()를 이용해 자릿수를 맞춰주자
padStart(maxLength, number) 문자의 자릿수를 맞춰주는 함수로 최대자릿수와 자릿수를 맞춰줄 문자를 매개변수로 갖는다.
1초에 한번씩 시간을 바꿔주기 위해 interval함수를 사용해주자.
setInterval(handler, timehandler) 반복적으로 나타내주고 싶을 때 사용하는 함수로 시간을 직접 정해줄 수 있다.(millisecond로 시간을 받는다. 1000ms = 1s)
모든 함수를 종합해서 자바스크립트로 함수를 만들어 현재시각을 만들어주자.
const clock = document.querySelector("#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);
원하는 포맷으로 시간이 잘 나온다.👍🏻👍🏻