|
1 | | -function setAlarm() {} |
| 1 | +let countdownInterval = null; |
| 2 | +let secondsLeft = 0; |
| 3 | + |
| 4 | +function setAlarm() { |
| 5 | + // Read the minutes from the input |
| 6 | + const input = document.getElementById("alarmSet"); |
| 7 | + const minutes = parseInt(input.value, 10); |
| 8 | + // If nothing useful was entered, do nothing |
| 9 | + if (isNaN(minutes) || minutes <= 0) { |
| 10 | + return; |
| 11 | + } |
| 12 | + // Convert to total seconds |
| 13 | + secondsLeft = minutes; |
| 14 | + // Stop any existing countdown |
| 15 | + if (countdownInterval !== null) { |
| 16 | + clearInterval(countdownInterval); |
| 17 | + countdownInterval = null; |
| 18 | + } |
| 19 | + // Show starting time right away |
| 20 | + updateTimeDisplay(); |
| 21 | + |
| 22 | + // Start the countdown |
| 23 | + countdownInterval = setInterval(() => { |
| 24 | + secondsLeft = secondsLeft - 1; |
| 25 | + |
| 26 | + updateTimeDisplay(); |
| 27 | + |
| 28 | + if (secondsLeft <= 0) { |
| 29 | + // Time's up |
| 30 | + clearInterval(countdownInterval); |
| 31 | + countdownInterval = null; |
| 32 | + secondsLeft = 0; |
| 33 | + // Makes sure to show exactly 00:00 |
| 34 | + updateTimeDisplay(); |
| 35 | + playAlarm(); |
| 36 | + } |
| 37 | + }, 1000); |
| 38 | +} |
| 39 | + |
| 40 | +// Helper function |
| 41 | +function updateTimeDisplay() { |
| 42 | + const minutes = Math.floor(secondsLeft / 60); |
| 43 | + const seconds = secondsLeft % 60; |
| 44 | + |
| 45 | + const displayMin = minutes.toString().padStart(2, "0"); |
| 46 | + const displaySec = seconds.toString().padStart(2, "0"); |
| 47 | + |
| 48 | + const heading = document.getElementById("timeRemaining"); |
| 49 | + heading.textContent = `Time Remaining: ${displayMin}:${displaySec}`; |
| 50 | +} |
2 | 51 |
|
3 | 52 | // DO NOT EDIT BELOW HERE |
4 | 53 |
|
|
0 commit comments