Skip to content

Commit 70d169d

Browse files
committed
Improve alarm reset and input handling
1 parent 6d5cccc commit 70d169d

2 files changed

Lines changed: 33 additions & 9 deletions

File tree

Sprint-3/alarmclock/alarmclock.js

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,19 @@
1-
function setAlarm() {}
2-
3-
// DO NOT EDIT BELOW HERE
41
let countdown;
52

3+
function getSecondsFromInput() {
4+
const inputValue = document.getElementById("alarmSet").value;
5+
const seconds = Number(inputValue);
6+
7+
// Keep only a safe whole number.
8+
if (!Number.isFinite(seconds) || seconds < 0) {
9+
return 0;
10+
}
11+
12+
return Math.floor(seconds);
13+
}
14+
615
function setAlarm() {
7-
let seconds = Number(document.getElementById("alarmSet").value);
16+
let seconds = getSecondsFromInput();
817

918
function updateDisplay() {
1019
let mins = Math.floor(seconds / 60);
@@ -15,8 +24,13 @@ function setAlarm() {
1524
"Time Remaining: " + mm + ":" + ss;
1625
}
1726

27+
// Reset old timer and sound before starting a new one.
28+
pauseAlarm();
1829
updateDisplay();
19-
clearInterval(countdown);
30+
31+
if (seconds <= 0) {
32+
return;
33+
}
2034

2135
countdown = setInterval(function () {
2236
seconds--;
@@ -37,7 +51,7 @@ function setup() {
3751
});
3852

3953
document.getElementById("stop").addEventListener("click", () => {
40-
pauseAlarm();
54+
stopAndReset();
4155
});
4256
}
4357

@@ -48,8 +62,18 @@ function playAlarm() {
4862
function pauseAlarm() {
4963
/* Stop the bell and freeze the timer */
5064
clearInterval(countdown);
51-
audio.pause();
52-
audio.currentTime = 0;
65+
try {
66+
audio.pause();
67+
audio.currentTime = 0;
68+
} catch (error) {
69+
// Audio can be missing in tests.
70+
}
71+
}
72+
73+
function stopAndReset() {
74+
pauseAlarm();
75+
document.getElementById("alarmSet").value = "";
76+
document.getElementById("timeRemaining").innerText = "Time Remaining: 00:00";
5377
}
5478

5579
window.onload = setup;

Sprint-3/alarmclock/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<meta charset="utf-8" />
55
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
66
<link rel="stylesheet" href="style.css" />
7-
<title>Title here</title>
7+
<title>Alarm clock app</title>
88
</head>
99
<body>
1010
<div class="centre">

0 commit comments

Comments
 (0)