Skip to content

Commit 426f1fb

Browse files
committed
fix: correct timer logic and prevent multiple intervals
1 parent 548ef16 commit 426f1fb

1 file changed

Lines changed: 16 additions & 14 deletions

File tree

Sprint-3/alarmclock/alarmclock.js

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,13 @@ function formatTime(totalSeconds) {
1818
return `Time Remaining: ${formattedMinutes}:${formattedSeconds}`;
1919
}
2020

21+
/**
22+
* Displays the remaining time.
23+
*/
24+
function displayTime() {
25+
titleElement.innerText = formatTime(timeRemainingInSeconds);
26+
}
27+
2128
/**
2229
* Updates the display and checks if the alarm should sound.
2330
*/
@@ -26,23 +33,11 @@ function updateTime() {
2633
displayTime();
2734

2835
if (timeRemainingInSeconds === 0) {
29-
titleElement.innerText = formatTime(0);
3036
playAlarm();
3137
document.body.classList.add("flash");
32-
return;
38+
clearInterval(alarmTimerIdentifier);
39+
alarmTimerIdentifier = null;
3340
}
34-
35-
alarmTimerIdentifier = setInterval(() => {
36-
updateTime();
37-
}, ONE_SECOND_IN_MILLISECONDS);
38-
}
39-
40-
/**
41-
* Displays the remaining time.
42-
*/
43-
function displayTime() {
44-
const titleElement = document.getElementById("timeRemaining");
45-
titleElement.innerText = formatTime(timeRemainingInSeconds);
4641
}
4742

4843
/**
@@ -73,6 +68,13 @@ function setAlarm() {
7368

7469
displayTime();
7570

71+
// Handle zero-second edge case
72+
if (timeRemainingInSeconds === 0) {
73+
playAlarm();
74+
document.body.classList.add("flash");
75+
return;
76+
}
77+
7678
alarmTimerIdentifier = setInterval(() => {
7779
updateTime();
7880
}, ONE_SECOND_IN_MILLISECONDS);

0 commit comments

Comments
 (0)