JS: 노마드 코더 5강 정리

ChoHyerin·2023년 5월 16일
0

Javascript

목록 보기
4/7

5.0 Intervals

~ 각 파일로 세분화 시켜서 코드를 저장하자 ~

index.html

    <h2 id="clock">00:00</h2>
	<!--위 내용을 추가함-->
    <h1 class="hidden" id="greeting"></h1>
    <script src="app.js"></script>
    <script src="js/greetings.js"></script>
    <script src="js/clock.js"></script>
  </body>

js/clock.js

const clock = document.querySelector("h2#clock");
//h2태그 안에 있는 id값으로 연결

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

setInterval(sayHello, 5000); // 5초 마다 sayHello 함수 불러오기

interval = 매번 일어나야 하는 무언가(간격)
>> setInterval(실행할 함수, 실행할 함수의 주기);

  • 후손 셀렉터(Descendent Selector) : '스페이스'로 연결
  • 자식 셀렉터(Child Selector) : ' >' 로 연결
    → ("h2 #id")로 하면 h2태그 안에 있는 id에 접근

→ ("h2#id") : h2태그 중 해당 ID를 가리킴


5.1 Timeouts and Dates

>Timeoust & Interval<

1) setInterval(실행함수, 주기)
: 함수를 주기(millisecond)마다 반복함

2) setTimeout(실행함수, 주기)
: 함수를 주기(millisecond)만큼 기다렸다 한 번만 실행

>Date<

: Date객체는 브라우저 안에 내장되어 있는 객체
const date = new Date(); 로 미리 선언하면 date.----();형식으로 사용가능

1) new Date().getHours()
: 시간 정보를 가져옴

2) new Date().getMinutes()
: 분 정보를 가져옴

3) new Date().getSeconds()
: 초 정보를 가져옴

clock.js

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

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

getClock();
setInterval(getClock, 1000);

>> 숫자가 이런 식으로 안 예뻐서 수정해야 함.


5.2 PadStart

1) padStart(length, 길이만큼 채울 내용) / padEnd(length, 길이만큼 채울 내용)
: length는 원하는 string의 길이이고 ,뒤에 원하는 길이가 되기 위해 채울 내용을 정함

→ Start면 앞부분부터 채워지고 End는 뒷 부분부터 채워짐

2) String()
: number를 string으로 바꾸는 방법은 String() 안에 감싸면 됨

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);

0개의 댓글