-
-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathalarmclock.js
More file actions
99 lines (75 loc) · 2.14 KB
/
alarmclock.js
File metadata and controls
99 lines (75 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
let timerInterval;
let flashInterval;
function setAlarm() {
const inputElement = document.getElementById("alarmSet");
const headingElement = document.getElementById("timeRemaining");
if (!inputElement.value) {
return;
}
let timeInSeconds = Number(inputElement.value);
if (isNaN(timeInSeconds) || timeInSeconds < 0) {
alert("Please enter a valid number of seconds.");
return;
}
if (timerInterval) {
clearInterval(timerInterval);
}
if (flashInterval) {
clearInterval(flashInterval);
}
function updateScreen(secondsRemaining) {
const minutes = Math.floor(secondsRemaining / 60);
const seconds = secondsRemaining % 60;
const formattedMinutes = String(minutes).padStart(2, "0");
const formattedSeconds = String(seconds).padStart(2, "0");
headingElement.innerText = `Time Remaining: ${formattedMinutes}:${formattedSeconds}`;
}
// update when we click set alarm
updateScreen(timeInSeconds);
timerInterval = setInterval(() => {
// Subtract 1 from the time
timeInSeconds = timeInSeconds - 1;
// Update the screen with the new time
updateScreen(timeInSeconds);
// when we hit zero?
if (timeInSeconds <= 0) {
clearInterval(timerInterval);
playAlarm();
flashScreen();
}
}, 1000);
}
function flashScreen() {
let flashCount = 0;
flashInterval = setInterval(() => {
flashCount++;
if (document.body.style.backgroundColor === "red") {
document.body.style.backgroundColor = "white";
} else {
document.body.style.backgroundColor = "red";
}
if (flashCount >= 20) {
clearInterval(flashInterval);
document.body.style.backgroundColor = "white";
}
}, 500);
}
// DO NOT EDIT BELOW HERE
var audio = new Audio("alarmsound.mp3");
function setup() {
document.getElementById("set").addEventListener("click", () => {
setAlarm();
});
document.getElementById("stop").addEventListener("click", () => {
pauseAlarm();
});
}
function playAlarm() {
audio.play();
}
function pauseAlarm() {
audio.pause();
clearInterval(flashInterval);
document.body.style.backgroundColor = "white";
}
window.onload = setup;