diff --git a/Sprint-3/alarmclock/alarmclock.js b/Sprint-3/alarmclock/alarmclock.js index 6ca81cd3b..d9ce6a275 100644 --- a/Sprint-3/alarmclock/alarmclock.js +++ b/Sprint-3/alarmclock/alarmclock.js @@ -1,4 +1,64 @@ -function setAlarm() {} +// need to set interval outside of setAlarm() so that every time the user clicks set alarm +// the previous interval is deleted. Otherwise there will be overlapping intervals +// if a user clicks on set alarm while an countdown is already active. +let intervalId = null; + +function setAlarm() { + const alarmClockInput = document.getElementById("alarmSet"); + const clockDisplay = document.getElementById("timeRemaining"); + let secondsRemaining = parseInt(alarmClockInput.value, 10); + + if (!isValidInput(secondsRemaining)) { + alert("please enter a valid positive integer!"); + return; + } + + clearInterval(intervalId); + + // display immediately on click; + const minutes = Math.floor(secondsRemaining / 60); + const seconds = secondsRemaining % 60; + displayTime(minutes, seconds, clockDisplay); + + intervalId = setInterval(() => { + secondsRemaining--; + + if (secondsRemaining <= 0) { + clearInterval(intervalId); + displayTime(0, 0, clockDisplay); + playAlarm(); + return; + } + + const minutes = Math.floor(secondsRemaining / 60); + const seconds = secondsRemaining % 60; + displayTime(minutes, seconds, clockDisplay); + }, 1000); +} + +// formats and displays countdown time to a supplied element +function displayTime(mins, secs, elem) { + const minsFormatted = String(mins).padStart(2, "0"); + const secsFormatted = String(secs).padStart(2, "0"); + elem.textContent = `Time Remaining: ${minsFormatted}:${secsFormatted}`; +} + +// returns true if input is an integer, false otherwise +function isValidInput(input) { + if (input === "" || isNaN(input)) { + return false; + } + + if (!Number.isInteger(input)) { + return false; + } + + if (input < 0) { + return false; + } + + return true; +} // DO NOT EDIT BELOW HERE diff --git a/Sprint-3/alarmclock/index.html b/Sprint-3/alarmclock/index.html index 48e2e80d9..89054f4b1 100644 --- a/Sprint-3/alarmclock/index.html +++ b/Sprint-3/alarmclock/index.html @@ -1,16 +1,16 @@ - + - Title here + Alarm clock app

Time Remaining: 00:00

- +