본문 바로가기
Study/Vanila JS

[노마드코더] 바닐라 JS로 크롬 앱 만들기 - 실시간 시계

by 22정민 2022. 12. 15.

https://nomadcoders.co/javascript-for-beginners

 

바닐라 JS로 크롬 앱 만들기 – 노마드 코더 Nomad Coders

Javascript for Beginners

nomadcoders.co

<!--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">
        <link rel="stylesheet" href="css/style.css" />
        <title>Momentum App</title>
    </head>
    <body>
        <form class="hidden" id="login-form">
        </form>
        <h2 id="clock">00:00:00</h2>
        <h1 class="hidden" id="greeting"></h1>
        <script src="js/greetings.js"></script>
        <script src="js/clock.js"></script>
    </body>
</html>

 

setInterval( function, time(단위:ms) );

- 매 time 마다 function이 호출되는 함수

setTimeout( function, time(단위:ms) );

- 정해진 time 후에 function이 호출되는 함수

//clock.js

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

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

//Call a function every 5000ms
setInterval(sayHello, 5000);

//Call a function after 5000ms
setTimeout(sayHello, 5000);

 

Date().getHours();

- 현재 시

Date().getMinutes();

- 현재 분

Date().getSeconds();

- 현재 초

//clock.js

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

function getClock() {
	const date = new Date();
    //현재 시각(시, 분, 초) 나타내기
    //1.console
    console.log(`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`);
    //2.html
    clock.innerText = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}

getClock();
//실시간으로 시간을 변경
setInterval(getClock, 1000);

 

str.padStart(targetLength [, padString])

 

- string에 사용 가능

- str의 길이가 2가 아니면, 앞쪽에 padString 추가해서 length 늘리기 가능

 

str.padEnd(targetLength [, padString])

- string에 사용 가능

- str의 길이가 2가 아니면, 뒷쪽에 padString 추가해서 length 늘리기 가능

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