|
1 | | -function setAlarm() {} |
| 1 | +// need to set interval outside of setAlarm() so that every time the user clicks set alarm |
| 2 | +// the previous interval is deleted. Otherwise there will be overlapping intervals |
| 3 | +// if a user clicks on set alarm while an countdown is already active. |
| 4 | +let intervalId = null; |
| 5 | + |
| 6 | +function setAlarm() { |
| 7 | + const alarmClockInput = document.getElementById("alarmSet"); |
| 8 | + const clockDisplay = document.getElementById("timeRemaining"); |
| 9 | + let secondsRemaining = parseInt(alarmClockInput.value, 10); |
| 10 | + |
| 11 | + if (!isValidInput(secondsRemaining)) { |
| 12 | + alert("please enter a valid positive integer!"); |
| 13 | + return; |
| 14 | + } |
| 15 | + |
| 16 | + clearInterval(intervalId); |
| 17 | + |
| 18 | + // display immediately on click; |
| 19 | + const minutes = Math.floor(secondsRemaining / 60); |
| 20 | + const seconds = secondsRemaining % 60; |
| 21 | + displayTime(minutes, seconds, clockDisplay); |
| 22 | + |
| 23 | + intervalId = setInterval(() => { |
| 24 | + secondsRemaining--; |
| 25 | + |
| 26 | + if (secondsRemaining <= 0) { |
| 27 | + clearInterval(intervalId); |
| 28 | + displayTime(0, 0, clockDisplay); |
| 29 | + playAlarm(); |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + const minutes = Math.floor(secondsRemaining / 60); |
| 34 | + const seconds = secondsRemaining % 60; |
| 35 | + displayTime(minutes, seconds, clockDisplay); |
| 36 | + }, 1000); |
| 37 | +} |
| 38 | + |
| 39 | +// formats and displays countdown time to a supplied element |
| 40 | +function displayTime(mins, secs, elem) { |
| 41 | + const minsFormatted = String(mins).padStart(2, "0"); |
| 42 | + const secsFormatted = String(secs).padStart(2, "0"); |
| 43 | + elem.textContent = `Time Remaining: ${minsFormatted}:${secsFormatted}`; |
| 44 | +} |
| 45 | + |
| 46 | +// returns true if input is an integer, false otherwise |
| 47 | +function isValidInput(input) { |
| 48 | + if (input === "" || isNaN(input)) { |
| 49 | + return false; |
| 50 | + } |
| 51 | + |
| 52 | + if (!Number.isInteger(input)) { |
| 53 | + return false; |
| 54 | + } |
| 55 | + |
| 56 | + if (input < 0) { |
| 57 | + return false; |
| 58 | + } |
| 59 | + |
| 60 | + return true; |
| 61 | +} |
2 | 62 |
|
3 | 63 | // DO NOT EDIT BELOW HERE |
4 | 64 |
|
|
0 commit comments