Javascript

[노마드코더] 바닐라JS 공부 5일차(clock :setInterval, setTimeout, Date 객체, padStart)

래모 2022. 1. 11. 22:55

setInterval(함수, 시간)

: 일정 시간 간격을 두고 함수를 실행하는 방법(밀리세컨드가 단위)

setTimeout(함수, 시간)

: 일정 시간 간격을 두고 함수를 실행하는 방법

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

setInterval(sayHello, 5000) // 5초에 한번씩 콘솔에 hello 출력

setTimeout(sayHello, 5000) // 5초 이후에 콘솔에 hello 출력 (그 이후엔 출력 되지 않음)

Date 객체

new Date() 를 호출하면 새로운 Date 객체가 만들어짐.

let now = new Date();
console.log(now); // 현재 날짜 및 시간이 보여짐

 

new Date(year, month, date, hours, minutes, seconds, ms)

   주어진 인수를 조합해 만들 수 있는 날짜가 저장된 객체가 반환됨

 

기본 함수

함수명 의미 설명
getFullYear() setFullYear() 년도  
getMonth() setMonth() 0~11 > 1월~12월
getDate() setDate()  
getDay() setDay() 요일 0~6 > 일요일 ~ 토요일
getHours() setHours() 시간  
 getHours() setHours()  
getMilliseconds() setMilliseconds() 밀리초  
getSeconds() setSeconds()  
getTime() setTime() Unix 타임 1970/1/1 12:00 기준 경과한 밀리 초

 

padStart(newLength, "padString")

: 현재 문자열의 시작을 다른 문자열로 채워 주어진 길이 값을 갖는 문자열을 반환함

무조건 String 형태를 받아야 함

var str = "Hi";

console.log(str.padStart(10));      // "        Hi"
console.log(str.padStart(10, "!")); // "!!!!!!!!Hi"

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Momentum App</title>
    <link rel = "stylesheet" href = "style.css">
    <style>
        .hidden { 
            display: none;
        }
    </style>
</head>
<body>
    <form class = "hidden" id = "login-form">
        <input required maxlength = "15" type = "text" placeholder = "What is your name?"/>
        <button>Log In</button>
    </form>
    <h1 id = "greeting" class = "hidden"></h1>
    <h2 id="clock">00:00:00</h2>
    <script src = "js/clock.js"></script>
    <script src = "js/greeting.js"></script>
</body>
</html>

 

clock.js

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

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