본문 바로가기
Dev/JavaScript

[JavaScript] Momentum App - 2.Clock

by 코딩삐약 2022. 5. 2.

// setInterval()

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

function sayHello() {
    console.log("hello");
}

//interval ex) 매 2초 마다 작동해야함
//setInterval(실행하고자 하는 function, 몇 ms마다 호출할 건지)
setInterval(sayHello, 5000);// 5초마다 sayHello 호출

// getClock()

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

function getClock(){
    const date = new Date();
    clock.innerText = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}

getClock(); //web site가 load되자마자 실행 후
setInterval(getClock, 1000);// 1초마다 실행

// padStart()

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

function getClock(){
    const date = new Date();
    const hours = String(date.getHours()).padStart(2, "0"); // String으로 형변환 후 앞에 0채우기
    const minutes = String(date.getMinutes()).padStart(2, "0"); // padStart(충족 길이, 안되면 채울 문자)
    const seconds = String(date.getSeconds()).padStart(2, "0");

    clock.innerText = `${hours}:${minutes}:${seconds}`;
}

getClock(); 
setInterval(getClock, 1000);