Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

개발자입니다

노마드코더 JS로 크롬앱만들기) #5 CLOCK - Date, setInterval, padStart 본문

Javascript/노마드코더 - JS로 크롬앱 만들기

노마드코더 JS로 크롬앱만들기) #5 CLOCK - Date, setInterval, padStart

끈기JK 2022. 9. 26. 15:09
<!-- index.html -->
<!doctype html>
<html>

<head>
    <link rel="stylesheet" href="css/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?" />
        <input type="submit" value="Log In" />
    </form>
    <h2 id="clock">00:00</h2>
    <h1 id="greeting" class="hidden"></h1>;
    <script src="js/greetings.js"></script>
    <script src="js/clock.js"></script>
</body>

</html>

 

■ clock 만들기

 

setInterval(함수, 시간(ms)) : 함수를 시간 설정한 간격마다 실행한다.

setTimeout(함수, 시간(ms)) : 함수를 설정 시간 이후 실행한다.

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

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

setInterval(sayHello, 5000);
setTimeout(sayHello, 2000);

 

 

-페이지에 시계 표시하기

getDate() : 오늘 날짜를 가져온다.

getDay() : 오늘 요일을 숫자로 가져온다. (일요일은 0, 월요일은 1, 화요일은 2, ...)

getHours(), getMinutes(), 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);

 

 

-시계 형식 00:00:00 고정하기

 

String.padStart(최대 길이, "문자") : String이 최대길이가 되지 않으면 문자로 채운다.

"1".padStart(2, "0")
'01'
// 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);