반응형
Countdown Timer
목표
카운트다운 타이머를 구현
기본 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Countdown Timer</title>
<link href='https://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="timer">
<div class="timer__controls">
<button data-time="20" class="timer__button">20 Secs</button>
<button data-time="300" class="timer__button">Work 5</button>
<button data-time="900" class="timer__button">Quick 15</button>
<button data-time="1200" class="timer__button">Snack 20</button>
<button data-time="3600" class="timer__button">Lunch Break</button>
<form name="customForm" id="custom">
<input type="text" name="minutes" placeholder="Enter Minutes">
</form>
</div>
<div class="display">
<h1 class="display__time-left"></h1>
<p class="display__end-time"></p>
</div>
</div>
<script src="scripts-START.js"></script>
</body>
</html>
과정
- 변수, 상수 생성
- 타이머를 진행하는 함수 생성
- 남은 시간을 출력하는 함수 생성
- 남은 시간, 분 생성
- 타이머 시간 설정
- 함수를 실행하도록 이벤트리스너 생성
코드 분석
1. 변수, 상수 생성
let countdown;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
변수 countdown
설정, 각 상수에 해당하는 내용 설정
- 타이머를 진행하는 함수 생성함수를 실행하면 현재 진행되고 있는
countdown
을 정지한다, 즉 기존에 실행했던 타이머를 초기화 시키고 현재 시간과 종료시간을 출력한다.
남은 시간을secondsLeft
에 담고 0초가 되면 카운트다운을 멈추고 그렇지 않다면 계속해서 1초마다 화면에 출력하고, 카운트를 실행한다 const timer = seconds => { clearInterval(countdown); const now = Date.now(); const then = now + seconds * 1000; displayTimeLeft(seconds); displayEndTime(then); countdown = setInterval(() => { const secondsLeft = Math.round((then - Date.now()) / 1000); if(secondsLeft < 0) { clearInterval(countdown); return; } displayTimeLeft(secondsLeft); }, 1000); }
2. 남은 시간을 출력하는 함수 생성
const displayTimeLeft = seconds => {
const minutes = Math.floor(seconds / 60);
const remainderSeconds = seconds % 60;
const display = `${minutes}:${remainderSeconds < 10 ? '0' : '' }${remainderSeconds}`;
document.title = display;
timerDisplay.textContent = display;
}
초단위로 입력한 값을 분:초 형식으로 출력하도록 설정해주고
탭의 타이틀도 남은 시간이 뜨도록 설정
3. 남은 시간, 분 설정
const displayEndTime = timestamp => {
const end = new Date(timestamp);
const hour = end.getHours();
const adjustedHour = hour > 12 ? hour - 12 : hour;
const minutes = end.getMinutes();
endTime.textContent = `Be Back At ${adjustedHour}:${minutes < 10 ? '0' : ''}${minutes}`;
}
남은 시간, 종료 시간을 출력할 수 있도록 현재 시간을 받아 상수 생성 후 표시
4. 타이머 시간 설정
const startTimer = e => {
const seconds = parseInt(e.target.dataset.time);
timer(seconds);
}
startTimer
함수로 seconds
에 타이머를 실행할 초를 담도록 한다.
5. 함수를 실행하도록 이벤트리스너 생성
buttons.forEach(button => button.addEventListener('click', startTimer));
document.customForm.addEventListener('submit', function(e) {
e.preventDefault();
const mins = e.target.minutes.value;
console.log(mins);
timer(mins * 60);
e.target.reset();
});
버튼을 누르면 startTimer
가 실행돼 타이머가 실행이 되고 각 변수에 대해 새로운 값들을 할당해 위의 함수에서 출력할 수 있도록 함