Skip to content

Commit 0f87e64

Browse files
committed
fix: validate input numbers to be positive integers only and stop timer from going below 0
1 parent 7a7eb43 commit 0f87e64

1 file changed

Lines changed: 28 additions & 4 deletions

File tree

Sprint-3/alarmclock/alarmclock.js

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,31 @@ function setAlarm() {
88
clearInterval(state.timerId);
99
state.timerId = null;
1010
}
11+
12+
const existingMessage = document.getElementById("error-message");
13+
if (existingMessage) {
14+
existingMessage.remove();
15+
}
16+
const displayedTime = document.getElementById("timeRemaining");
1117
const timeInput = document.getElementById("alarmSet");
18+
1219
state.remainingTime = +timeInput.value;
20+
if (state.remainingTime <= 0 || !Number.isInteger(state.remainingTime)) {
21+
state.remainingTime = 0;
22+
displayedTime.textContent = `Time Remaining: 00:00`;
23+
timeInput.value = "";
24+
25+
const container = document.querySelector(".centre");
26+
const errorMessage = document.createElement("p");
27+
errorMessage.id = "error-message";
28+
errorMessage.textContent = "Please enter a positive whole number";
29+
errorMessage.style.color = "red";
30+
container.appendChild(errorMessage);
31+
return;
32+
}
1333
const formattedTime = formatTime(state.remainingTime);
1434
timeInput.value = "";
1535

16-
const displayedTime = document.getElementById("timeRemaining");
1736
displayedTime.textContent = `Time Remaining: ${formattedTime}`;
1837

1938
state.timerId = setInterval(timer, 1000);
@@ -31,15 +50,20 @@ function formatTime(seconds) {
3150

3251
function timer() {
3352
const displayedTime = document.getElementById("timeRemaining");
53+
3454
state.remainingTime -= 1;
35-
const countingDownTime = formatTime(state.remainingTime);
36-
displayedTime.textContent = `Time Remaining: ${countingDownTime}`;
37-
if (state.remainingTime === 0) {
55+
56+
if (state.remainingTime <= 0) {
57+
state.remainingTime = 0;
58+
displayedTime.textContent = `Time Remaining: 00:00`;
3859
clearInterval(state.timerId);
3960
state.timerId = null;
4061
document.body.style.backgroundColor = "red";
4162
playAlarm();
63+
return;
4264
}
65+
const countingDownTime = formatTime(state.remainingTime);
66+
displayedTime.textContent = `Time Remaining: ${countingDownTime}`;
4367
}
4468

4569
// DO NOT EDIT BELOW HERE

0 commit comments

Comments
 (0)