HTML
<!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">
<title>Document</title>
<link rel="stylesheet" href="test.css">
</head>
<body>
<h1 id="clock"></h1>
<script src="test.js"></script>
</body>
</html>
자바스크립트
const clock = document.querySelector("#clock"); //id clock인 태그를 지정
function getClock () {
const date = new Date();
const hours = String(date.getHours()).padStart(2, "0"); //현재 시간을 가져온다 string의 길이가 2가 안된다면 앞에 0을 붙힌다
const minutes = String(date.getMinutes()).padStart(2, "0"); //현재 분을 가져운다 string의 길이가 2가 안된다면 앞에 0을 붙힌다
const seconds = String(date.getSeconds()).padStart(2, "0"); //현재 초를 가져온다 string의 길이가 2가 안된다면 앞에 0을 붙힌다
clock.innerText = `${hours}:${minutes}:${seconds}`;
}; //html의 id가 clock인 태그에 함수들을 저장
getClock(); //함수를 미리 호출함으로써 1초동안 안보이는걸 방지
setInterval(getClock, 1000); //getClock 함수를 1초마다 실행