⏲노마드코더 Vanilla JS CLOCK

소연·2021년 7월 3일
0

vanillaJS

목록 보기
6/8

Clock

const clock = document.querySelector("h2#clock");

HTML에서 id="clock"을 변수 clock으로 생성.

function getClock(){
    const date = new Date();
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");
    clock.innerText = `${hours}:${minutes}:${seconds}`;
}

new Date();는 자바스크립트에 있는 날짜함수로 현재 날짜 및 시간을 알려준다
date 변수 설정 후, date.getHours(시간), date.getMinutes(분), date.getSeconds(초)
각각의 변수 설정
padStart()의 역할은 padStart(스트링의 길이, "앞에 추가할 문자");
단, 날짜 함수는 스트링(문자열)으로 이루어진 것이 아닌 넘버(숫자)로 이루어져 있기때문에 padStart를 숫자를 문자열로 바꿔주어야 사용 가능
따라서 변수값을 설정할 때 String(값)으로 묶어주어 문자열로 변경한다.(그 반대도 가능)

getClock();
setInterval(getClock, 1000);

setInterval을 통해 getClock이 1초에 한번씩 나타나도록 반복(1/1000초 단위로 표현)
이 명령만 하면 초기값이 뜬 후 1초 뒤에 getClock이 실행되므로 getClock(); 을 사용하여 바로 실행될 수 있도록 한다

CLOCK JS 전체 코드

const clock = document.querySelector("h2#clock");

function getClock(){
    const date = new Date();
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");
    clock.innerText = `${hours}:${minutes}:${seconds}`;
}

getClock()
setInterval(getClock, 1000);
profile
코린이🤪

0개의 댓글