ETC -

타입스크립트 live Countdown Timer

  • -

👉타입스크립트 live Countdown Timer기능 만들기

타입스크립트를 사용해서 live Countdown Timer기능을 만들어 보겠습니다.!

타입스크립트에서 DOM에 접근할때 짧은 '$'로 접근하기위해서 함수를 만들었습니다.(제이쿼리 처럼 사용)

const $ = (select: string): Element[] => {
  return Array.from(document.querySelectorAll(select));
};

👉전체코드 공유

여기서 주의깊에 봐야한것은 template라는 기본 템플릿 변수에서 {{__countdown__}}라는 특수문자?를 썼는데
이 부분에서 특정 템플릿을 넣을수가 있습니다.

template = template.replace('{{__countdown__}}', timeOnTemplate());

위에 코드를 살펴보면 {{__countdown__}}에다가 timeOnTemplate()함수를 덮어씌우겠다는 의미 입니다.

import './init.css'
import './style.css'

const $ = (select: string): Element[] => {
  return Array.from(document.querySelectorAll(select));
};

const originalTemplate = `
  <div class="date-time-section">
    {{__countdown__}}
  </div>
`;

const countDown = () => {
  const countDownEndDate: Date = new Date('2024-03-10'); //마감날짜를 설정합니다.
  let template = originalTemplate;

  const countdownfunction = setInterval(() => {
    const now: Date = new Date();
    const distance = countDownEndDate.getTime() - now.getTime(); // 마감 날짜(시간) - 현재 날짜(시간) 설정 되는곳!
    
    let days: string = String(Math.floor(distance / (1000 * 60 * 60 * 24)));
    let hours: string = String(Math.floor(
      (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
    ));
    let minutes: string = String(Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)));
    let seconds: string = String(Math.floor((distance % (1000 * 60)) / 1000));

    days = String(days).padStart(2, "0");
    hours = String(hours).padStart(2, "0");
    minutes = String(minutes).padStart(2, "0");
    seconds = String(seconds).padStart(2, "0");

    const timeTemplate = (value: string, label: string, isLast?: boolean) => `
      <div class="time">
        <p class="time-text">${value}</p>
        <p class="time-label">${label}</p>
      </div>${isLast ? "" : "<span>:</span>"}
    `;

    const timeOnTemplate = () => (`
      <div class="time-on">
        ${timeTemplate(days, "DAYS")}
        ${timeTemplate(hours, "HOURS")}
        ${timeTemplate(minutes, "MINUTES")}
        ${timeTemplate(seconds, "SECONDS", true)}
      </div>`
    );

    template = originalTemplate; // 매 반복마다 원본 템플릿으로 초기화

    if (distance < 0) { // 투표가 끝났을 때 동작
      clearInterval(countdownfunction);
      const timeOffTemplate = () => (`
        <div class="time-off">
          ${timeTemplate("00", "DAYS")}
          ${timeTemplate("00", "HOURS")}
          ${timeTemplate("00", "MINUTES")}
          ${timeTemplate("00", "SECONDS", true)}
        </div>
        `
      );

      template = template.replace('{{__countdown__}}', timeOffTemplate());
    }

    template = template.replace('{{__countdown__}}', timeOnTemplate());
    $("#app")[0].innerHTML = template;
  }, 10);
};

(() => {
  countDown();
})();

replace를 사용한 특정 부분에 template넣는 방법을 살펴봤습니다.
React와 비교를 하면 컴포넌트에서 {children}를 사용하는것과 비슷한것 입니다.😃😃

👉코드 공유

countdown-Timer.zip
0.01MB

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.