|
| 1 | +let countdown; |
| 2 | + |
| 3 | +const timerDisplay = document.querySelector('.display__time-left'); |
| 4 | +const endTime = document.querySelector('.display__end-time'); |
| 5 | +const buttons = document.querySelectorAll('[data-time]'); |
| 6 | + |
| 7 | + |
| 8 | +function timer(seconds) { |
| 9 | + clearInterval(countdown); |
| 10 | + |
| 11 | + const now = Date.now(); |
| 12 | + const then = now + seconds * 1000; |
| 13 | + displayTime(seconds); |
| 14 | + displayEndTime(then); |
| 15 | + countdown = setInterval(() => { |
| 16 | + const secondsLeft = Math.round((then - Date.now()) / 1000); |
| 17 | + |
| 18 | + if (secondsLeft < 0){ |
| 19 | + clearInterval(countdown); |
| 20 | + return; |
| 21 | + } |
| 22 | + |
| 23 | + displayTime(secondsLeft); |
| 24 | + }, 1000); |
| 25 | +} |
| 26 | + |
| 27 | +function displayTime(seconds) { |
| 28 | + const minutes = Math.floor(seconds / 60); |
| 29 | + const remainingSeconds = seconds % 60; |
| 30 | + const display = `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`; |
| 31 | + document.title = display; |
| 32 | + timerDisplay.textContent = display; |
| 33 | +} |
| 34 | + |
| 35 | + |
| 36 | +function displayEndTime(timestamp) { |
| 37 | + const end = new Date(timestamp); |
| 38 | + const hours = end.getHours(); |
| 39 | + const minutes = end.getMinutes(); |
| 40 | + |
| 41 | + endTime.textContent = `Be Back At ${hours > 12 ? hours - 12 : hours}:${minutes < 10 ? '0' : ''}${minutes}`; |
| 42 | +} |
| 43 | + |
| 44 | + |
| 45 | +function startTimer() { |
| 46 | + const seconds = this.dataset.time; |
| 47 | + timer(seconds); |
| 48 | +} |
| 49 | +buttons.forEach(button => button.addEventListener('click', startTimer)); |
| 50 | + |
| 51 | + |
| 52 | +document.customForm.addEventListener('submit', function(e) { |
| 53 | + e.preventDefault(); |
| 54 | + const mins = this.minutes.value; |
| 55 | + timer(mins * 60); |
| 56 | + this.reset(); |
| 57 | +}); |
0 commit comments