diff --git a/Sprint-3/alarmclock/alarmclock.js b/Sprint-3/alarmclock/alarmclock.js index 6ca81cd3b..864c9dff0 100644 --- a/Sprint-3/alarmclock/alarmclock.js +++ b/Sprint-3/alarmclock/alarmclock.js @@ -1,4 +1,67 @@ -function setAlarm() {} +let countdownTimerId = null; + +const finishedBackgroundColor = "#007BA7"; +const normalBackgroundColor = ""; + +function setAlarm() { + // Resets background each time user sets a new alarm (optional but nice) + document.body.style.backgroundColor = normalBackgroundColor; + + // Stops any previous countdown + stops any currently playing alarm sound + if (countdownTimerId !== null) clearInterval(countdownTimerId); + pauseAlarm(); + + const input = document.getElementById("alarmSet"); + + // only allows positive integers + const seconds = Number(input.value); + const isValid = Number.isInteger(seconds) && seconds > 0; + + if (!isValid) { + input.setCustomValidity("Please enter a whole number greater than 0."); + input.reportValidity(); + return; + } + input.setCustomValidity(""); + + // Reads the number of seconds the user typed + let totalSecRemaining = + parseInt(document.getElementById("alarmSet").value, 10) || 0; + + // Element that displays: "Time Remaining: MM:SS" + const timeRemainingTitle = document.getElementById("timeRemaining"); + + // Updates the title based on totalSecRemaining + const renderTimeRemaining = () => { + const minutesRemaining = String( + Math.floor(totalSecRemaining / 60) + ).padStart(2, "0"); + const secondsRemaining = String(totalSecRemaining % 60).padStart(2, "0"); + timeRemainingTitle.textContent = `Time Remaining: ${minutesRemaining}:${secondsRemaining}`; + }; + + // Shows the starting value after clicking "Set Alarm" + renderTimeRemaining(); + + // Runs every second countdown tick + countdownTimerId = setInterval(() => { + // If time is up, stops ticking and starts the alarm sound + if (totalSecRemaining <= 0) { + clearInterval(countdownTimerId); + countdownTimerId = null; + + // Change background when alarm finishes + document.body.style.backgroundColor = finishedBackgroundColor; + + playAlarm(); + return; + } + + // Otherwise subtracts 1 second and update the display + totalSecRemaining -= 1; + renderTimeRemaining(); + }, 1000); +} // DO NOT EDIT BELOW HERE diff --git a/Sprint-3/alarmclock/index.html b/Sprint-3/alarmclock/index.html index 48e2e80d9..36715d7d9 100644 --- a/Sprint-3/alarmclock/index.html +++ b/Sprint-3/alarmclock/index.html @@ -1,20 +1,23 @@ -
- - - -