Digital Clock

yoon Y·2022년 2월 10일
0

Vanilla Project

목록 보기
7/13

Digital Clock 래퍼런스

알게된 점

현재의 날짜+시간 데이터를 가져오는 함수 구현

const addZero = (num: number): string => {
  return num < 10 ? '0' + num : '' + num;
};

const getHourInfo = (hh: number): HourObj => {
  if (hh > 12) {
    return {
      hour: addZero(hh - 12),
      time: 'PM',
    };
  }
  return {
    hour: addZero(hh),
    time: 'AM',
  };
};

export const getCurrentDate = (): DateValues => {
  const today = new Date();
  const dayList = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
  return {
    hh: getHourInfo(today.getHours()),
    mm: addZero(today.getMinutes()),
    ss: addZero(today.getSeconds()),
    YY: today.getFullYear(),
    MM: today.getMonth() + 1,
    DD: today.getDate(),
    dd: dayList[today.getDay()].toUpperCase(),
  };
};

원하는 대로 모양대로 포맷해주는 함수도 있었다

내가 구현한 방법처럼 일일이 구하는 것보다 훨씬 편한 방법 같다

    const options = {
        weekday: 'short',
        hour: 'numeric',
        minute: 'numeric',
    };

    const time = new Intl.DateTimeFormat('en', options)
        .format(new Date())
        .toUpperCase();
    timeArea.textContent = time;

setInterval의 콜백함수 관련 트러블

반복 함수를 걸어주는 과정에서 콜백함수를 this.setState로 바로 넣어주니 this.render가 인식되지 않아 실행이 안됐다 → 더 알아봐야겠음

// (x)
 mount() {
   setInterval(
     this.setState
   , 1000);
 }

// (o)
 mount() {
   setInterval(() => {
     this.setState();
   }, 1000);
 }

코드

class DigitalClock extends Component<undefined> {
  state: DateValues;
  constructor($target: Element) {
    super($target);
    this.state;
    this.setState();
    this.mount();
  }

  template() {
    return `
      <div class='digital-clock-container'>
        <div class='digital-clock'>
          <h1> ${this.state.dd}</h1>
          <h1> ${this.state.hh.hour}</h1> 
          <h1> ${this.state.mm}</h1> 
          <h1> ${this.state.ss}</h1> 
          <h1> ${this.state.hh.time}</h1>
        </div>
      </div>
    `;
  }

  render() {
    this.$target.innerHTML = '';
    this.$target.innerHTML = this.template();
  }

  setState() {
    this.state = getCurrentDate();
    this.render();
  }

  mount() {
    setInterval(() => {
      this.setState();
    }, 1000);
    console.log(this.state);
  }
}

export default DigitalClock;
profile
#프론트엔드

0개의 댓글