From b0c04055c5bc4c02e680e2d9c6c9b0d604437bac Mon Sep 17 00:00:00 2001 From: changicho Date: Sun, 5 Jul 2020 14:05:44 +0900 Subject: [PATCH] Feat: Add 29 - Countdown Timer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ?: setInterval을 이용한 countdown interval이 중복 되는것을 막기 위한 clearInterval을 사용 --- 29 - Countdown Timer/changi.js | 60 +++++++++++++++++++++++++++++++++ 29 - Countdown Timer/index.html | 53 ++++++++++++++++------------- 2 files changed, 89 insertions(+), 24 deletions(-) create mode 100644 29 - Countdown Timer/changi.js diff --git a/29 - Countdown Timer/changi.js b/29 - Countdown Timer/changi.js new file mode 100644 index 0000000..adfecb8 --- /dev/null +++ b/29 - Countdown Timer/changi.js @@ -0,0 +1,60 @@ +let countdown; // interval +const timerDisplay = document.querySelector(".display__time-left"); +const endTime = document.querySelector(".display__end-time"); +const buttons = document.querySelectorAll("[data-time]"); + +function 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); +} + +function 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; +} + +function 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}`; +} + +function startTimer() { + const seconds = parseInt(this.dataset.time); + timer(seconds); +} + +buttons.forEach((button) => button.addEventListener("click", startTimer)); + +// get time from form tag +document.customForm.addEventListener("submit", function (e) { + e.preventDefault(); + const mins = this.minutes.value; + console.log(mins); + timer(mins * 60); + this.reset(); +}); diff --git a/29 - Countdown Timer/index.html b/29 - Countdown Timer/index.html index d54f447..ab4465a 100644 --- a/29 - Countdown Timer/index.html +++ b/29 - Countdown Timer/index.html @@ -1,29 +1,34 @@ - - - Countdown Timer - - - - -
-
- - - - - -
- -
+ + + Countdown Timer + + + + +
+
+ + + + + +
+ +
+
+
+

+

+
-
-

-

-
-
- - + + +