Making a JS Clock
1. 시계 만들기 : 현재 시간을 출력
1. Date 객체의 활용
const date = new date();
date.getDate() //오늘 날짜
date.getHours() //지금 시간
date.getMinutes() //지금 분
date.getSeconds() //지금 초
date.getDay() //오늘 요일2. SetInterval
두 인자 값을 받아 실행하는 함수
//say hi!라는 문자열을 콘솔에 3초에 1번씩 실행
function sayHi(){
console.log("say hi!");
}
setInterval(sayHi, 3000); //1 millisecond 방식3. Ternary Operator(삼항 연산자, mini if)
3-1. 문자열 예시
clockTitle.innerText = `${seconds < 10 ? `0${seconds}` : seconds}`;
//초가 < 10보다 작다면 ?(if)
//초 앞에 0을 붙여주고
//: (else) 아니라면 초를 그대로 나타내줘~!3-2. 삼항연산자를 이용한 00시 00분 설정
<!DOCTYPE html>
<html>
<head>
<title>Momentum</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="js-clock">
<div class="js-title">
<h1>00:00</h1>
</div>
</div>
<script src="clock.js"></script>
</body>
</html>const clockContainer = document.querySelector(".js-clock"),
//;대신 ,로 깔끔하게 정리 const clockTitle에 const 생략
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();Last updated
Was this helpful?