IT/개발

#5 [2021 UPDATE] CLOCK

공장장J 2022. 3. 30. 09:44
반응형

#5.0 Intervals
interval은 매번 일어나야 하는 무언가를 의미한다.
매 2초마다 무슨일이 일어나길 원할 때 사용. 이미 자바스크립트에 내장되어 있음
setInterval()
두개의 argument를 받는다. 첫째는 내가 실행하고자 하는 function 함수. 두번째는 function을 몇ms 간격으로 할지
5000ms = 5s(5초)
function sayHello() {
console.log("hello");
}
setInterval(sayHello, 5000);
5초마다 콘솔에 hello가 나타난다.
==========================
#5.1 Timeouts and Dates
function을 딱 한번 호출하는데, 일정 시간이 흐른 뒤에 호출하는 것.
setInterval과 비슷하게 두개의 argument를 받는다.
setTImeout(실행할 함수, 얼마나 기다릴지ms단위로 넣어줌);
function sayHello() {
console.log("hello");
}

setTimeout(sayHello, 5000);
5초 뒤 한번만 실행된다.
날짜, 시간, 분, 초 가져오기
new Date().getDate()
new Date().getHours()
new Date().getMinutes()
new Date().getSeconds()
<index.html>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Momentum App</title>
</head>
<body>
<form id="login-form" class="hidden">
<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/greetings.js "></script>
<script src="js/clock.js"></script>
</body>
</html>

<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 함수
padStart(2, "0")
1 -> 01 의 형태로 만들어 줌. 앞에 문자 채우기
padStart(원하는 길이, "빈칸에 채울 것")

padEnd(2, "0")
1 -> 10

getHours()는 숫자가 나와서 바로 padStart()를 사용할 수 없다. padStrat는 string. 즉 문자만 상대함
따라서 getHours()로 받은 숫자를 string으로 변경해줘야한다.
String() 괄호 안에 적으면 숫자가 문자로 변경된다.

콘솔 화면

==========================
#5.3
==========================

반응형