개발/javascript

자바스크립트 실습 - Making a JS Clock

JH._.kim 2021. 4. 19. 14:08

노마드코더 바닐라 JS로 크롬 앱 만들기 #3.0 ~ #3.1 강의 들으며 정리.

 

 

html

<div class="js-clock">
    <h1>00:00</h1>
 </div>

 

js

const clockContainer = document.querySelector('.js-clock'),
      clockTitle = clockContainer.querySelector('h1');

 

변수를 만들 때 콤마를 이용해서 const를 여러번 작성하지 않고 간단하게 작성해줄 수 있다.

 

function init(){
  getTime();
};

init();

 

init이라는 함수를 만들어주고 그 안에 시간을 가져올 getTime이라는 함수를 넣어준다.

 

function getTime(){
  const date = new Date();
  const minutes = date.getMinutes();
  const hours = date.getHours();
  const seconds = date.getSeconds();
};

 

오늘 날짜의 시간, 분, 초의 정보를 가져온다.

 

function getTime(){
  const date = new Date();
  const minutes = date.getMinutes();
  const hours = date.getHours();
  const seconds = date.getSeconds();
  clockTitle.innerText = 
  `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
};

 

ternary operator(삼항연산자)는 미니 if라고 생각하면 된다. if 명령문의 단축 형태

 

조건 ? 값1 : 값2

 

조건이 참이면 값1을 반환하고 거짓이면 값2를 반환한다.

위의 식은 시간, 분, 초가 10보다 작을 때는 앞에 0이 붙도록 해준다.

예를 들면 10 : 5 : 6 이런 식이 아니라 10 : 05 : 06 이런 식으로 표시되도록 한다

 

 

function init(){
  getTime();
  setInterval(getTime, 1000);
};

init();

 

마지막으로 setInterval를 이용해서 시간이 반복되도록 한다.

 

 

이렇게 하면 최종 완성본

 

const clockContainer = document.querySelector('.js-clock'),
      clockTitle = clockContainer.querySelector('h1');

function getTime(){
  const date = new Date();
  const minutes = date.getMinutes();
  const hours = date.getHours();
  const seconds = date.getSeconds();
  clockTitle.innerText = 
  `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
};

function init(){
  getTime();
  setInterval(getTime, 1000);
};

init();

 

 

시계만들기는 해본 적 있어서 그렇게 어렵지 않았는데 이 다음부터가 좀 어려웠다..

 

 

728x90