javascript 현재 시각 표시하기

이승민·2020년 5월 6일
0

javascript를 이용하여 웹페이지 화면에 현재 시각을 표시해보자.

  • html
<!DOCTIYE HTML>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>test</title>
	<link href = 'first.css' rel = 'stylesheet' type='text/css'/>
</head>
<body>
	<h1 id="title" class="other">what time is it?!</h1>
	<div class="js-clock">
		<h2>00:00</h2>
	</div>
	<script src='second.js'></script>
<body>
<html>
  • js
const clockContainer = document.querySelector('.js-clock'), // js-clock 이라는 class를 가져와 clockContainer 라는 변수로 선언하였다.
      clockTitle = clockContainer.querySelector('h2'); // js-clock 이라는 class안에 있는 h2 태그를 가져와 clockTitle 이라는 변수로 선언하였다.

function getTime () { // 화면에 실시간으로 시간을 노출하기 위한 함수
	const date = new Date(); // 현재 실시간 date 정보를 가져와 date 라는 변수로 선언하였다.
	const minutes = date.getMinutes(); // 현재 실시간 date 정보 중 Minutes(분) 을 minutes 변수로 선언하였다.
	const hours = date.getHours(); // 현재 실시간 date 정보 중 Hours(시) 를 hours 변수로 선언하였다.
	const seconds = date.getSeconds(); // 현재 실시간 date 정보 중 Seconds(초) 를 seconds 변수로 선언하였다.
	clockTitle.innerText =  // 이전에 clockTitle이라는 변수로 선언해두었던 h2 태그에 대체할 텍스를 입력한다.
        `${ 
		hours < 10 ? `0${hours}` : hours 
	} : ${
		minutes < 10 ? `0${minutes}` : minutes
	} : ${
		seconds < 10 ? `0${seconds}` : seconds
	}`;
} // 00:00:00 형태로 노출되며 조건문 없이 입력하게 되면 10 미만 숫자의 경우 01,02 와 같이 2자리로 표기되지 않고 1,2 와 같이 한자리 수로 표시되기 때문에 해당 숫자가 10 미만일 경우 0을 붙인 상태로 표기하도록 조건문을 적용한다.

function time () { // 앞서 작성했던 getTime 이라는 함수를 작동시키기 위한 함수
	getTime();
	setInterval(time, 1000); // setInterval 함수는 어떠한 함수를 얼마 주기로 실행할 것인지를 설정한다. 이 경우 time 이라는 함수를 1000 millisecond 주기로 실행한다는 의미이다. 1000 millisecond = 1 second
}
time();
  • 결과물

profile
프론트 앤드 개발자를 꿈꿉니다.

0개의 댓글