본문 바로가기

그 땐 Front했지/그 땐 JavaScript했지

[Nomad/바닐라 JS Challenges] 8일차 | Ch05 CLOCK

728x90

참고자료: 노마드 코더 바닐라 JS로 크롬 앱 만들기 https://nomadcoders.co/javascript-for-beginners/lobby

0.  Intervals


 

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="css/style.css" />
    <title>Momentum App</title>
  </head>
  <body>
    <form class="hidden" id="login-form">
      <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 class="hidden" id="greeting"></h1>
    
    <script src="greetings.js"></script>
    <script src="clock.js"></script>
  </body>
</html>
clock.js
const clock = document.querySelector("h2#clock");

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

setInterval(sayHello, 5000);

✍🏻setInterval: 정해진 시간마다 지정한 함수를 실행한다.

 

1. Timeouts and Dates


 

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

👉🏻setInterval 함수를 이용해 getClock함수를 1초마다 실행해 시계를 만들었다!

👉🏻Date 클래스의 메서드를 이용해 현재 시각을 가져온다.

  • getHours
  • getMinutes
  • getSeconds

 

2. PadStart


clock.js
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}`;
}

✍🏻padStart(a, b): 앞쪽에 패딩을 넣어달라고 부탁하는 함수

  • 첫 번째 인자: 패딩까지 합해 만들 문자열 길이
  • 두 번째 인자: 패딩에 채워넣을 문자

💡내가 겪는 오류들은 이미 많은 개발자들이 겪었을 것이고 많은 개발자들이 겪은 오류라면 그 해결책이 함수로 나왔을 가능성이 높다!

728x90