diff --git a/Sprint-3/alarmclock/alarmclock.js b/Sprint-3/alarmclock/alarmclock.js index 6ca81cd3b..964c6c415 100644 --- a/Sprint-3/alarmclock/alarmclock.js +++ b/Sprint-3/alarmclock/alarmclock.js @@ -1,4 +1,59 @@ -function setAlarm() {} +let countdownTimerId = null; + +function resetAlarmState() { + if (countdownTimerId !== null) { + clearInterval(countdownTimerId); + countdownTimerId = null; + } + + // Ensure alarm audio from previous runs is stopped before a new countdown. + if (audio && !audio.paused) { + pauseAlarm(); + } +} + +function setAlarm() { + const heading = document.getElementById("timeRemaining"); + const input = document.getElementById("alarmSet"); + + let remainingSeconds = Number(input.value); + + if (!Number.isFinite(remainingSeconds) || remainingSeconds < 0) { + remainingSeconds = 0; + } + + remainingSeconds = Math.floor(remainingSeconds); + + resetAlarmState(); + + const updateHeading = () => { + const minutes = Math.floor(remainingSeconds / 60) + .toString() + .padStart(2, "0"); + const seconds = (remainingSeconds % 60).toString().padStart(2, "0"); + heading.innerText = `Time Remaining: ${minutes}:${seconds}`; + }; + + updateHeading(); + + if (remainingSeconds === 0) { + playAlarm(); + return; + } + + countdownTimerId = setInterval(() => { + if (remainingSeconds > 0) { + remainingSeconds -= 1; + updateHeading(); + } + + if (remainingSeconds === 0) { + clearInterval(countdownTimerId); + countdownTimerId = null; + playAlarm(); + } + }, 1000); +} // DO NOT EDIT BELOW HERE @@ -10,7 +65,7 @@ function setup() { }); document.getElementById("stop").addEventListener("click", () => { - pauseAlarm(); + resetAlarmState(); }); } diff --git a/Sprint-3/alarmclock/index.html b/Sprint-3/alarmclock/index.html index 48e2e80d9..ff2d3b453 100644 --- a/Sprint-3/alarmclock/index.html +++ b/Sprint-3/alarmclock/index.html @@ -4,7 +4,7 @@ -