Front-end/Vanilla JS 이것저것
2. 시계 초침을 움직여보자 ( setInterval )
자곰
2023. 11. 23. 17:55
setInterval을 통한 일정주기로 변하는 애니메이션을 구현해보고자 합니다
HTML and CSS
간단하게 시 분 초를 나타내는 침과 시계모양을 만들었습니다
JavaScript 설명
// 현재 시간을 가져와 각 시계 바늘의 각도를 계산하고 적용하는 함수입니다.
function setTime() {
// 현재 시간을 가져옵니다.
const now = new Date();
// 현재 시, 분, 초를 추출합니다.
const hours = now.getHours();
const mins = now.getMinutes();
const seconds = now.getSeconds();
// 각 바늘의 각도를 계산합니다.
const secondsDegree = (seconds / 60) * 360 + 90;
const minDegree = (mins / 60) * 360 + 90;
const hoursDegree = (hours / 12) * 360 + (mins / 60) * 30 + 90;
// 각 바늘에 계산된 각도를 적용하여 회전시킵니다.
secondHand.style.transform = `rotate(${secondsDegree}deg)`;
minHand.style.transform = `rotate(${minDegree}deg)`;
hourHand.style.transform = `rotate(${hoursDegree}deg)`;
}
// 1초마다 setTime 함수를 호출하여 시간이 실시간으로 업데이트되도록 합니다.
setInterval(() => {
setTime();
}, 1000);
// 페이지 로딩 시 초기 시간을 설정합니다.
setTime();
시연 및 결과물
See the Pen Untitled by jun (@nate1994) on CodePen.
회고
1. rotate 함수를 이용한 각도 조절
2. setInterval안에 콜백으로 실행할 함수를 초기에 한번 실행해주는 과정의 필요성
3. Date객체 사용