728x90
현재 시간을 다음과 같이 시:분:초로 나타내는 시계를 구현한다.
index.html 코드
<!DOCTYPE html>
<html lang="en">
<head>
...(생략)...
</head>
<body>
<h2 id="clock"></h2>
<script src="clock.js"></script>
</body>
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.inerText = `${hours}:${minutes}:${seconds}`;
}
getClock();
setInterval(getClock, 1000);
1. clock 선언
- querySelector 사용
const clock = document.querySelector("h2#clock");
- getElementById 사용
const clock = document.getElementById("clock");
2. getClock() 선언
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}`;
}
3. setInterval() 설정
setInterval(getClock, 1000);
→ 1초마다 getClock()을 반복 실행하여 1초씩 시간이 바뀐다.
↓ 관련 개념 정리글 ↓
https://it-amin.tistory.com/62
728x90
반응형
'개발 공부 > Javascript' 카테고리의 다른 글
[Javascript 기본] 간단한 시계 구현(Date 객체, getHours(), getMinutes(), getSeconds(), padStart(), setInterval()) (2) | 2022.09.22 |
---|