forked from wesbos/JavaScript30
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
66 lines (51 loc) · 1.96 KB
/
scripts.js
File metadata and controls
66 lines (51 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
let countdown;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
const timer = function timer(seconds) {
clearInterval(countdown); // clear exiting timers
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);
};
const displayTimeLeft = function displayTimeLeft(seconds) {
let secondsRemaining = seconds;
const hours = Math.floor(secondsRemaining / 3600);
secondsRemaining = secondsRemaining % 3600;
const minutes = Math.floor(secondsRemaining / 60);
secondsRemaining = secondsRemaining % 60;
const displayHours = hours > 0 ? `${hours}:` : '';
const displayMins = minutes < 10 ? `0${minutes}` : minutes;
const displaySeconds = secondsRemaining < 10 ? `0${secondsRemaining}` : secondsRemaining;
const display = `${displayHours}${displayMins}:${displaySeconds}`;
document.title = display;
timerDisplay.textContent = display;
};
const displayEndTime = 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}`;
};
const startTimer = function startTimer() {
const seconds = parseInt(this.dataset.time);
timer(seconds);
};
const startCustomTimer = function startCustomTimer(e) {
e.preventDefault();
const mins = parseInt(this.minutes.value);
timer(mins * 60);
this.reset();
};
buttons.forEach(button => button.addEventListener('click', startTimer));
document.customForm.addEventListener('submit', startCustomTimer);