JS - building a clock

suyeon·2023년 6월 20일
0

Vanilla.js

목록 보기
10/13
post-thumbnail

building a clock

setInterval(), setTimeout()

: setInterval() 의 경우 웹페이지의 특정 부분을 주기적으로 업데이트 해줘야하거나 변경된 데이터를 주기적으로 받아와야 하는 경우 사용한다(ex. 시계).

setTimeout() 은 실행하고자 하는 함수를 일정시간 이후에 실행시켜준다.

  • Syntax
setInterval(실행하려는 함수, 반복주기(millisec));
setTimeout(실행하려는 함수, 일정시간(millisec));

Date 객체

: Date 객체를 활용하면 생성 및 수정 시간을 저장하거나 시간을 측정할 수 있고, 현재 날짜를 출력하는 용도로도 활용할 수 있다. new Date() 을 호출하면 새로운 Date 객체가 만들어진다.

getHours()
getMinutes()
getSeconds()
getFullYear()
getMonth()

...

등등의 메서드를 사용해 날짜/시간에 관한 정보를 얻을 수 있다.

// 인수없이 호출하면 현재 날짜와 시간이 저장된 객체가 반환됨.
const date = new Date();
console.log(date); // -> Tue Jun 20 2023 20:38:25 GMT+0900 (Korean Standard Time)

padStart()

: padStart 메서드는 현재 문자열의 시작을 다른 문자열로 채워 주어진 길이를 만족하는 새로운 문자열을 반환한다.

  • Syntax
String.padStart(targetLength, padString);

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

function getClock() {
  const date = new Date();
  const hour = String(date.getHours()).padStart(2, 0); //padStart() 메서드는 문자열을 변형하므로 Date 객체에서 가져오는 값을 문자열(String)로 바꿔주어야 한다. => String()
  const minute = String(date.getMinutes()).padStart(2, 0);
  const second = String(date.getSeconds()).padStart(2, 0);
  
  clock.innerText = `${hour}:${minute}:${second}`
}

getClock();
setInterval(getClock, 1000);

참고

profile
coding & others

0개의 댓글