forked from simranlotey/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alarmclock.js
54 lines (42 loc) · 1.05 KB
/
alarmclock.js
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
const display = document.getElementById("clock");
const audio = new Audio("alarm.mp3.mp3");
audio.loop = true;
let alarmTime = null;
let alarmTimeout = null;
function updateTime() {
const date = new Date();
const hour = formatTime(date.getHours());
const minutes = formatTime(date.getMinutes());
const seconds = formatTime(date.getSeconds());
display.innerText = hour + " : " + minutes + " : " + seconds;
}
function formatTime(time) {
if (time < 10) {
return "0" + time;
}
return time;
}
setInterval(updateTime, 1000);
function setAlarmTime(value) {
alarmTime = value;
}
function setAlarm() {
if (alarmTime) {
const current = new Date();
const timeToAlarm = new Date(alarmTime);
if (timeToAlarm > current) {
const timeout = timeToAlarm.getTime() - current.getTime();
alarmTimeout = setTimeout(function() {
audio.play();
}, timeout);
alert("Alarm set");
}
}
}
function clearAlarm() {
audio.pause();
if (alarmTimeout) {
clearTimeout(alarmTimeout);
alert("Alarm cleared");
}
}