본문 바로가기

js

make clock with vanilaJS

vanilaJS로 초 단위로 흘러가는 시계 만들기!(setInterval, conditinal Expression)


1. html file


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1 id="title" class="btn">This works!</h1>
<script src="index.js"></script>

<div class="js-clock"><h1>00:00</h1></div>

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


2. clock.js


const clockContainer = document.querySelector(".js-clock"),
clockTitle = clockContainer.querySelector("h1");

function getTime() {
const date = new Date();
const minutes = date.getMinutes();
const hours = date.getHours();
const seconds = date.getSeconds();
clockTitle.innerText = `${hours}:${minutes}:${seconds}`;
}
function init() {
getTime();
}

init();


3. result



4. add setInterval()! and Conditional Expressions(삼항 연산자)


Conditional Expressions ?


if(a > b)

 z = a;           ->     z = (a>b) ? a : b  

else

 z = b;


const clockContainer = document.querySelector(".js-clock"),
clockTitle = clockContainer.querySelector("h1");

function getTime() {
const date = new Date();
const minutes = date.getMinutes();
const hours = date.getHours();
const seconds = date.getSeconds();
clockTitle.innerText = `${hours < 10 ? `0${hours}` : hours}:${
minutes < 10 ? `0${minutes}` : minutes
}:${
seconds < 10 ? `0${seconds}` : seconds
//3항 연산자, 시, 분 초 가 10보다 작을 경우 0을 붙여서! 아니면 그냥 원래 값을 보여줘라
}`;
}
function init() {
getTime();
setInterval(getTime, 1000);
// millisecond 단위 라서 000을 붙여 줘야 1초가 된다.
}

init();


5. final result



'js' 카테고리의 다른 글