Skip to content

Commit 2e8421b

Browse files
committed
Refactor alarm clock logic: validation, reset state, unified display, improved flash toggle.
1 parent d724dbc commit 2e8421b

1 file changed

Lines changed: 40 additions & 17 deletions

File tree

‎Sprint-3/alarmclock/alarmclock.js‎

Lines changed: 40 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,60 @@
1+
let intervalId = null;
2+
13
function setAlarm() {
24
const input = document.getElementById("alarmSet");
35
const heading = document.getElementById("timeRemaining");
46

5-
let remainingSeconds = Number(input.value);
6-
7-
function formatTime(totalSeconds) {
8-
const minutes = Math.floor(totalSeconds / 60);
9-
const seconds = totalSeconds % 60;
10-
11-
const mm = String(minutes).padStart(2, "0");
12-
const ss = String(seconds).padStart(2, "0");
13-
14-
return `${mm}:${ss}`;
7+
const value = Number(input.value);
8+
if (!Number.isInteger(value) || value <= 0) {
9+
alert("Please enter a positive whole number of seconds.");
10+
return;
1511
}
1612

17-
heading.innerText = `Time Remaining: ${formatTime(remainingSeconds)}`;
13+
resetAlarm();
1814

19-
const intervalId = setInterval(() => {
15+
let remainingSeconds = value;
16+
updateDisplay(remainingSeconds);
17+
18+
intervalId = setInterval(() => {
2019
remainingSeconds -= 1;
2120

2221
if (remainingSeconds > 0) {
23-
heading.innerText = `Time Remaining: ${formatTime(remainingSeconds)}`;
22+
updateDisplay(remainingSeconds);
2423
} else {
25-
heading.innerText = "Time Remaining: 00:00";
24+
updateDisplay(0);
2625
clearInterval(intervalId);
2726
playAlarm();
28-
document.body.classList.add("flash");
27+
setFlashingBackground(true);
2928
}
3029
}, 1000);
3130
}
3231

33-
function stopFlashingBackground() {
34-
document.body.classList.remove("flash");
32+
function resetAlarm() {
33+
clearInterval(intervalId);
34+
intervalId = null;
35+
updateDisplay(0);
36+
setFlashingBackground(false);
37+
}
38+
39+
function updateDisplay(seconds) {
40+
const heading = document.getElementById("timeRemaining");
41+
heading.innerText = `Time Remaining: ${formatTime(seconds)}`;
42+
}
43+
44+
function formatTime(totalSeconds) {
45+
const minutes = Math.floor(totalSeconds / 60);
46+
const seconds = totalSeconds % 60;
47+
const mm = String(minutes).padStart(2, "0");
48+
const ss = String(seconds).padStart(2, "0");
49+
return `${mm}:${ss}`;
50+
}
51+
52+
function setFlashingBackground(isFlashing) {
53+
if (isFlashing) {
54+
document.body.classList.add("flash");
55+
} else {
56+
document.body.classList.remove("flash");
57+
}
3558
}
3659

3760
// DO NOT EDIT BELOW HERE

0 commit comments

Comments
 (0)