시계 만들기

jini.choi·2022년 5월 18일
0

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</title>
    <link rel="stylesheet" href="css/style.css" />
</head>
<body>
    <h2 id="clock">00:00:00</h2>

    <script src="js/clock.js"></script>
</body>
</html>

JS(24시간제)

const clock = document.querySelector("#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() //getClock을 먼저 한번 호출해야 시계가 바로 뜸
setInterval(getClock, 1000); 

//padStart(string이 가져야 하는 길이, 그렇지 않을경우 앞쪽에 비어있는 만큼 문자 추가)
  • padStart를 한 이유는 시계가 1의 자리 일때 18:43:1 처럼 못나게 나와서 문자 길이가 2미만 일 때 앞에 0으로 채워줌

  • padStartpadEnd의 pad가 css의 padding이랑 같은 완충재 혹은 덧대는 뭔가를 뜻함

  • getHours, getMinutes등등은 number타입이기 때문에 padStart를 할 수 없음

  • String constructor로 감싸주어 문자열로 만들어준 다음 padStart를 작성


다른 방법(12시간제)

function getClock(){
	clock.innerText = new Date().toLocaleTimeString();
}

getClock()
setInterval(getClock, 1000);

이 글은 패스트캠퍼스 노마드코더 '바닐라 JS로 크롬 앱 만들기'을 수강하며 정리한 노트입니다.
https://nomadcoders.co/javascript-for-beginners/lobby

profile
개발짜🏃‍♀️

0개의 댓글