소스 코드
JavaScript30/02 - JS and CSS Clock/index-START.html at master · jisunipark/JavaScript30
30 Day Vanilla JS Challenge. Contribute to jisunipark/JavaScript30 development by creating an account on GitHub.
github.com
Today I Learned
Date객체와 setInterval 함께 사용하기
Date 객체와 setInterval 메서드 각각에 대해서는 이해하고 있었지만, setInterval의 첫 번째 인수로 전달하는 콜백 함수 내에서 Date객체를 적절히 활용하면 이렇게 시계 인터페이스도 구현해볼 수 있다니 흥미롭다.
const secondHand = document.querySelector('.second-hand');
const minuteHand = document.querySelector('.min-hand');
const hourHand = document.querySelector('.hour-hand');
function setDate() {
const now = new Date();
const seconds = now.getSeconds();
const secondsDegrees = (seconds / 60) * 360 + 90;
secondHand.style.transform = `rotate(${secondsDegrees}deg)`;
const minutes = now.getMinutes();
const minutesDegrees = (minutes / 60) * 360 + 90;
minuteHand.style.transform = `rotate(${minutesDegrees}deg)`;
const hours = now.getHours();
const hoursDegrees = (hours / 12) * 360 + 90;
hourHand.style.transform = `rotate(${hoursDegrees}deg)`;
}
setInterval(setDate, 1000);
이 두 가지를 이용해서 시계 UI 뿐만 아니라 타이머나 알람 같은 것들도 구현해볼 수 있겠다.
참고
W3Schools.com
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
'스터디 > JavaScript30' 카테고리의 다른 글
[JavaScript30] 05 - Flex Panel Gallery (0) | 2024.12.10 |
---|---|
[JavaScript30] 04 - Array Cardio Day 1 (0) | 2024.12.07 |
[JavaScript30] 03 - CSS Variables (1) | 2024.12.07 |
[JavaScript30] 01 - JavaScript Drum Kit (3) | 2024.12.06 |