Skip to content

Commit b60f5ca

Browse files
Refactor: improve readability and reuse functions in alarm clock
1 parent 28e240a commit b60f5ca

3 files changed

Lines changed: 30 additions & 24 deletions

File tree

Sprint-3/alarmclock/alarmclock.js

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,34 @@
1+
const input = document.querySelector("#alarmSet");
2+
let timeRemainingEl = document.querySelector("#timeRemaining");
13
function setAlarm() {
2-
const input = document.querySelector("#alarmSet");
3-
let seconds = input.value%60;
4-
let minutes = (input.value - seconds)/60;
5-
const timeRemaining = document.querySelector("#timeRemaining");
6-
timeRemaining.textContent = `Time Remaining: ${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
7-
givenTime = Number(input.value);
8-
clearInterval(timerId);
9-
timerId =setInterval(()=>
10-
{
4+
if (!input.value) {
5+
alert("Enter minutes");
6+
return;
7+
}
8+
givenTime = Number(input.value);
9+
updateTime();
10+
clearInterval(timerId);
11+
timerId = setInterval(() => {
1112
givenTime = givenTime - 1;
1213
updateTime();
13-
if (givenTime === 0) {
14-
clearInterval(timerId);
15-
playAlarm();
16-
}
14+
if (givenTime <= 0) {
15+
clearInterval(timerId);
16+
playAlarm();
17+
return;
18+
}
1719
}, 1000);
18-
1920
}
20-
let timerId;
21-
let givenTime;
22-
23-
function updateTime(){
24-
let seconds = givenTime%60;
25-
let minutes = (givenTime - seconds)/60;
26-
const remainingTime = document.querySelector("#timeRemaining");
27-
remainingTime.textContent = `Time Remaining: ${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
21+
let timerId;
22+
let givenTime;
23+
function formatTime(givenTime) {
24+
let seconds = givenTime % 60;
25+
let minutes = Math.floor(givenTime / 60);
26+
return `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
2827
}
2928

29+
function updateTime() {
30+
timeRemainingEl.textContent = `Time Remaining: ${formatTime(givenTime)}`;
31+
}
3032

3133
// DO NOT EDIT BELOW HERE
3234

Sprint-3/alarmclock/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
<div class="centre">
1111
<h1 id="timeRemaining">Time Remaining: 00:00</h1>
1212
<label for="alarmSet">Set time to:</label>
13-
<input id="alarmSet" type="number" />
13+
<input id="alarmSet" type="number" min="1" max="60" required placeholder="Enter minutes" />
1414

1515
<button id="set" type="button">Set Alarm</button>
1616
<button id="stop" type="button">Stop Alarm</button>

Sprint-3/alarmclock/style.css

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,11 @@
77
}
88

99
#alarmSet {
10-
margin: 20px;
10+
margin: 15px;
11+
width: 150px;
12+
padding: 2px;
13+
font-size: 16px;
14+
border-radius: 5px;
1115
}
1216

1317
h1 {

0 commit comments

Comments
 (0)