interval이란 매번 일어나야하는 무언가를 말함
만약 매 2초마다 무언가 일어나게 하고 싶다면 interval임
1초는 1000ms임
매초마다 반복적으로 시간을 업데이트해줘야하니까 Interval을 쓰는게 맞음.
또한 1초 interval을 쓰면 처음 웹 사이트를 로드 했을 때, 1초 뒤에 시계가 표시되는 문제가 있기에, 바로 getClock이라는 함수를 실행시켜줌.
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 App</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>
<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>
JS
const clock = document.querySelector("#clock");
function getClock() {
const date = new Date();
clock.innerText = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}
getClock();
setInterval(getClock, 1000);
여기서 문제는 시간 중에 초가 00, 01, 02 이렇게 뜨는 것이 아닌, 0,1,2,,이렇게 뜨는 문제가 발생함.
-> 그럴려면 string이 minimum 2개의 숫자를 갖게 하면 됨
padStart() 라는 함수는
"문자".padStart(숫자,"문자")
로 쓰이는데 앞에 숫자는 string의 길이, 뒤에 문자는 만약 길이가 안되었을 때 시작 부분에 채워졌으면 하는 문자임.
padEnd 도 있음
JS (문제 해결) number을 string(문자)로 바꿔주기도 했음(padStart를 쓰기 위해서)
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);