Skip to content

Commit 87eda84

Browse files
committed
Day 29 complete
1 parent 8e62a58 commit 87eda84

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

29 - Countdown Timer/scripts.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
let countdown;
2+
const timerDisplay = document.querySelector('.display__time-left');
3+
const endTime = document.querySelector('.display__end-time');
4+
const buttons = document.querySelectorAll('[data-time]');
5+
6+
function timer(seconds) {
7+
clearInterval(countdown);
8+
9+
const now = Date.now();
10+
const then = now + seconds * 1000;
11+
12+
displayTimeLeft(seconds);
13+
displayEndTime(then);
14+
15+
countdown = setInterval(() => {
16+
const secondsLeft = Math.round((then - Date.now()) / 1000);
17+
if(secondsLeft < 0) {
18+
clearInterval(countdown);
19+
} else {
20+
displayTimeLeft(secondsLeft);
21+
}
22+
}, 1000);
23+
}
24+
25+
function secondsToTime(sec) {
26+
const H = Math.floor(sec / 3600);
27+
const m = Math.floor((sec % 3600) / 60);
28+
const s = sec % 60;
29+
30+
return H + ':' + twoDigitNum(m) + ':' + twoDigitNum(s);
31+
}
32+
33+
function twoDigitNum(num) {
34+
const pad = (num < 10) ? '0' : '';
35+
return pad + num;
36+
}
37+
38+
function displayTimeLeft(seconds) {
39+
const display = secondsToTime(seconds);
40+
document.title = display;
41+
timerDisplay.textContent = display;
42+
}
43+
function displayEndTime(timestamp) {
44+
const end = new Date(timestamp);
45+
const hour = end.getHours();
46+
const adjustedHour = hour > 12 ? hour - 12 : hour;
47+
const minutes = end.getMinutes();
48+
endTime.textContent = `Be Back At ${adjustedHour}:${twoDigitNum(minutes)}`;
49+
}
50+
51+
function startTimer(event) { timer(event.target.dataset.time); }
52+
53+
function handleForm(event) {
54+
event.preventDefault();
55+
timer(document.customForm.minutes.value * 60);
56+
document.customForm.reset();
57+
}
58+
59+
buttons.forEach(button => button.addEventListener('click', startTimer));
60+
document.customForm.addEventListener('submit', handleForm);

0 commit comments

Comments
 (0)