diff --git a/Sprint-3/alarmclock/alarmclock.js b/Sprint-3/alarmclock/alarmclock.js index 6ca81cd3b..c49c568b1 100644 --- a/Sprint-3/alarmclock/alarmclock.js +++ b/Sprint-3/alarmclock/alarmclock.js @@ -1,4 +1,61 @@ -function setAlarm() {} +function setAlarm() { + const input = document.getElementById("alarmSet"); + const heading = document.getElementById("timeRemaining"); + + // Read and trim input + const raw = input.value.trim(); + + // If input is empty, do nothing (don't start the alarm) + if (raw === "") { + heading.innerText = `Time Remaining: 00:00`; + return; + } + + // Parse total seconds from input + let totalSeconds = parseInt(raw, 10); + if (Number.isNaN(totalSeconds) || totalSeconds <= 0) { + // invalid or non-positive input -> do nothing + heading.innerText = `Time Remaining: 00:00`; + return; + } + + // Format seconds into "MM:SS" + function formatTime(seconds) { + const minutes = Math.floor(seconds / 60); + const secs = seconds % 60; + return `Time Remaining: ${String(minutes).padStart(2, "0")}:${String( + secs + ).padStart(2, "0")}`; + } + + // Immediately set the heading to the initial value + heading.innerText = formatTime(totalSeconds); + + // If a previous interval exists, clear it so we only have one running + if (window._alarmInterval) { + clearInterval(window._alarmInterval); + window._alarmInterval = null; + } + + // Start counting down every 1000ms + window._alarmInterval = setInterval(() => { + totalSeconds -= 1; + + if (totalSeconds <= 0) { + // update to 00:00, stop interval and play alarm + heading.innerText = formatTime(0); + clearInterval(window._alarmInterval); + window._alarmInterval = null; + if (typeof playAlarm === "function") { + playAlarm(); + } + } else { + // update heading with remaining time + heading.innerText = formatTime(totalSeconds); + } + }, 1000); +} + // DO NOT EDIT BELOW HERE 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 @@ -