Skip to content

Commit 50a0653

Browse files
committed
Updated code to reflected all 6 improvements recommended
1 parent 80cc2eb commit 50a0653

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

Sprint-3/alarmclock/alarmclock.js

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,33 @@
1+
// Constants for time conversion
2+
const SECONDS_PER_MINUTE = 60;
3+
const MILLISECONDS_PER_SECOND = 1000;
4+
15
let intervalId;
26

37
function setAlarm() {
48
const input = document.getElementById("alarmSet");
5-
let time = Number(input.value);
6-
79
const heading = document.getElementById("timeRemaining");
810

9-
clearInterval(intervalId);
11+
let totalSeconds = Number(input.value);
1012

11-
function format(num) {
12-
if (num < 10) return "0" + num;
13-
return num;
13+
// Input validation: check for invalid or non-positive numbers
14+
if (isNaN(totalSeconds) || totalSeconds <= 0) {
15+
heading.innerText = "Please enter a valid positive number of seconds";
16+
return;
1417
}
1518

19+
clearInterval(intervalId);
20+
1621
heading.innerText =
1722
"Time Remaining: " +
18-
format(Math.floor(time / 60)) +
23+
String(Math.floor(totalSeconds / SECONDS_PER_MINUTE)).padStart(2, "0") +
1924
":" +
20-
format(time % 60);
25+
String(totalSeconds % SECONDS_PER_MINUTE).padStart(2, "0");
2126

2227
intervalId = setInterval(() => {
23-
time--;
28+
totalSeconds--;
2429

25-
if (time <= 0) {
30+
if (totalSeconds <= 0) {
2631
heading.innerText = "Time Remaining: 00:00";
2732
clearInterval(intervalId);
2833
playAlarm();
@@ -31,10 +36,10 @@ function setAlarm() {
3136

3237
heading.innerText =
3338
"Time Remaining: " +
34-
format(Math.floor(time / 60)) +
39+
String(Math.floor(totalSeconds / SECONDS_PER_MINUTE)).padStart(2, "0") +
3540
":" +
36-
format(time % 60);
37-
}, 1000);
41+
String(totalSeconds % SECONDS_PER_MINUTE).padStart(2, "0");
42+
}, MILLISECONDS_PER_SECOND);
3843
}
3944
// DO NOT EDIT BELOW HERE
4045

0 commit comments

Comments
 (0)