js 카운트다운

Semmy·2022년 5월 18일
0

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>
  <h1>Time Until ChristmasDay !</h1> 
  <h2 id="clock"></h2>

    <script src="src/clock.js"></script>
  </body>
</html>

clock.js

const clock = document.querySelector("h2#clock");
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;

function getClock() {
  const xmas = new Date("2022-12-25 00:00:00+0900");
  const today = new Date();
  const gap = xmas - today;
  const days = Math.floor(gap / day);
  const hours = Math.floor((gap % day) / hour);
  const minutes = Math.floor((gap % hour) / minute);
  const seconds = Math.floor((gap % minute) / second);
  const hoursStr = String(hours).padStart(2, "0");
  const minutesStr = String(minutes).padStart(2, "0");
  const secondsStr = String(seconds).padStart(2, "0");
  clock.innerText = `${days}d ${hoursStr}h ${minutesStr}m ${secondsStr}s`;
}
getClock();
setInterval(getClock, 1000);

xmas 와 today 의 날짜를 빼서 gap을 구해준다.
Math.floor를 이용해서 같거나 작은 수 중에 가장 큰 정수를 반환한다.
시, 분과 초는 한자리수일때 앞에 "0"을 추가해주기 위해서 padStart를 이용하였다.

완성된 모습이다!

profile
Web Developer

0개의 댓글