Skip to content

Commit c073696

Browse files
committed
Completed lesson 29
Just in the nick of time, too!
1 parent 939cff1 commit c073696

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
const now = Date.now();
9+
const then = now + seconds * 1000;
10+
displayTimeLeft(seconds);
11+
displayEndTime(then);
12+
countdown = setInterval(() => {
13+
const secondsLeft = Math.round((then - Date.now()) / 1000);
14+
// check if we should stop it
15+
if (secondsLeft < 0) {
16+
clearInterval(countdown);
17+
return;
18+
}
19+
// display it
20+
displayTimeLeft(secondsLeft);
21+
}, 1000);
22+
}
23+
24+
function displayTimeLeft(seconds) {
25+
const minutes = Math.floor(seconds / 60);
26+
const remainderSeconds = seconds % 60;
27+
const display = `${minutes}:${remainderSeconds < 10 ? '0' : ''}${remainderSeconds}`;
28+
document.title = display;
29+
timerDisplay.textContent = display;
30+
}
31+
32+
function displayEndTime(timestamp) {
33+
const end = new Date(timestamp);
34+
const hour = end.getHours();
35+
const minutes = end.getMinutes();
36+
endTime.textContent = `Be back at ${hour > 12 ? hour - 12 : hour }:${minutes < 10 ? '0' : ''}${minutes}`;
37+
}
38+
39+
function startTimer() {
40+
const seconds = parseInt(this.dataset.time);
41+
timer(seconds);
42+
}
43+
44+
buttons.forEach(button => button.addEventListener('click', startTimer));
45+
document.customForm.addEventListener('submit', function(e) {
46+
e.preventDefault();
47+
const mins = this.minutes.value;
48+
timer(mins * 60);
49+
this.reset();
50+
});

0 commit comments

Comments
 (0)