Skip to content

Commit 944fea3

Browse files
committed
feat: improve alarm functionality with input validation and timer reset
1 parent 435d330 commit 944fea3

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

Sprint-3/alarmclock/alarmclock.js

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,43 @@
1+
let currentTimerId = null;
2+
13
function setAlarm() {
24
const input = document.getElementById("alarmSet");
35
const heading = document.getElementById("timeRemaining");
46
let seconds = Number(input.value);
57

8+
// Sanitise input
9+
if (!Number.isInteger(seconds) || seconds <= 0) {
10+
alert("Please enter a positive whole number");
11+
return;
12+
}
13+
14+
// Reset before starting new countdown
15+
if (currentTimerId !== null) {
16+
clearInterval(currentTimerId);
17+
}
18+
19+
pauseAlarm();
20+
21+
document.body.style.backgroundColor = "";
22+
623
function updateDisplay(remainingSeconds) {
724
const minutes = Math.floor(remainingSeconds / 60);
825
const secs = remainingSeconds % 60;
926
const formattedTime = `${String(minutes).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
1027
heading.textContent = `Time Remaining: ${formattedTime}`;
11-
document.body.style.backgroundColor = "";
1228
}
1329

1430
// Set initial display
1531
updateDisplay(seconds);
1632

1733
// Start countdown
18-
const timerId = setInterval(() => {
34+
currentTimerId = setInterval(() => {
1935
seconds--;
2036
updateDisplay(seconds);
2137

2238
if (seconds <= 0) {
23-
clearInterval(timerId);
39+
clearInterval(currentTimerId);
40+
currentTimerId = null;
2441
playAlarm();
2542
document.body.style.backgroundColor = "red";
2643
}

0 commit comments

Comments
 (0)