오늘은 업무중에 카운트다운을 구현 할 일이 생겨서 구현해보았다.
date를 다루기에 Moment라는 좋은 라이브러리가 있지만 날짜나 시간을 계산하는것이 아니라 단순히 카운트 다운만 하면되는것이여서 라이브러를 사용하지 않기로 했다.
Moment.js는 자바스크립트에서 dates를 다루기 위한 Swiss Army knife(맥가이버칼)이다. 깔끔하고 간결한 API를 이용해서 날짜와 시간을 분석, 검증, 조작, 표시할 수 있다.
아래는 카운트다운을 표기할 html을 작성한 코드이다.
index.html
<div class="bnner-countdown" >STANDBY OPENS IN
<span id="countdown"></span>
</div>
index.js
const targetDate = new Date(2023, 2, 25, 0, 0, 0);
function updateCountdown() {
const currentDate = new Date();
const diff = targetDate - currentDate;
const days = Math.floor(diff / (1000 * 60 * 60 * 24)).toString().padStart(2, '0');
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0');
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
const seconds = Math.floor((diff % (1000 * 60)) / 1000).toString().padStart(2, '0');
const countdown = document.getElementById("countdown");
countdown.innerHTML = `${days}:${hours}:${minutes}:${seconds}`;
}
setInterval(updateCountdown, 1000);
updateCountdown이라는 함수를 만들고 1초마다 함수를 호출할 한다.
1초마다 시간을 update해줘야 하기 때문이다.
targetDate는 카운트 다운을 지정할 날짜와 시간이다.
currentDate는 현재 날짜를 Date객체로 받아와서 사용한다.
반복적으로 함수를 호출해야 했기때문에 setInterval() 사용했다.