Skip to content

Commit 7df742b

Browse files
committed
Changes to Alarm Clock
1 parent 96d077b commit 7df742b

1 file changed

Lines changed: 44 additions & 1 deletion

File tree

Sprint-3/alarmclock/alarmclock.js

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,47 @@
1-
function setAlarm() {}
1+
let countdownId = null;
2+
3+
function formatTime(totalSeconds) {// Convert total seconds to minutes and seconds
4+
const minutes = Math.floor(totalSeconds / 60);
5+
const seconds = totalSeconds % 60;
6+
7+
return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
8+
}
9+
10+
function updateHeading(totalSeconds) {// Update the heading with the formatted time remaining
11+
const heading = document.getElementById("timeRemaining");// Get the heading element using its DOM ID
12+
heading.innerText = `Time Remaining: ${formatTime(totalSeconds)}`;// Set the text of the heading to show the time remaining in the format "Time Remaining: MM:SS"
13+
}
14+
15+
function setAlarm() {
16+
const input = document.getElementById("alarmSet");// Get the input element using its DOM ID
17+
let remainingSeconds = Number(input.value);// Convert the input value to a number representing the total seconds for the countdown
18+
19+
if (!Number.isFinite(remainingSeconds) || remainingSeconds < 0) {// Check if the input is a valid number and non-negative
20+
remainingSeconds = 0;// If the input is invalid, set remainingSeconds to 0
21+
}
22+
23+
if (countdownId !== null) {// If there is an existing countdown, clear it before starting a new one
24+
25+
clearInterval(countdownId);
26+
}
27+
28+
updateHeading(remainingSeconds);// Update the heading to show the initial time remaining before starting the countdown
29+
30+
countdownId = setInterval(() => {// Start a new interval that will execute the provided function every 1000 milliseconds (1 second)
31+
remainingSeconds -= 1;
32+
33+
if (remainingSeconds <= 0) {// If the remaining seconds reach 0 or below, stop the countdown and play the alarm
34+
updateHeading(0);
35+
clearInterval(countdownId);
36+
countdownId = null;
37+
playAlarm();
38+
document.body.style.backgroundColor = "red"; // change background colour
39+
return;
40+
}
41+
42+
updateHeading(remainingSeconds);
43+
}, 1000);
44+
}
245

346
// DO NOT EDIT BELOW HERE
447

0 commit comments

Comments
 (0)