DEV Community 👩‍💻👨‍💻

Cover image for Digital Clock with Alarm in JavaScript + HTML
The Dev Drawer
The Dev Drawer

Posted on

Digital Clock with Alarm in JavaScript + HTML

Have you ever wanted to build your own alarm clock but lacked the tools and hardware needed? Well, why not make one using JavaScript and HTML?

In this tutorial, I show you how to make your own alarm clock that gives you the ability to display the time digitally and set an alarm that works. Simple code using vanilla JavaScript, HTML, and CSS only.

Build your own alarm clock in just 30 minutes.

View This On YouTube

File Structure

index.html
/sass
     style.scss
/js
     clock.js
/css (generated by Sass)
   style.css
   style.min.css
/sounds
   alarm.mp3
bg.jpg
logo.png
Enter fullscreen mode Exit fullscreen mode

Our HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clock with Alarm</title>
    <link rel="stylesheet" href="/css/style.min.css">
</head>
<body>
    <div class="main">
        <div id="time"></div>
        <div id="alarm">
            <span></span>
            <button type="button" id="turnoff_alarm">Turn Off Alarm</button>
            <audio id="alarm_audio" loop muted autoplay src="/sounds/alarm.mp3"></audio>
        </div>
    </div>
    <script src="/js/clock.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The basic HTML is simple and has a time div, an alarm div, a place for the alarm audio, and a button.

Our Clock JS Class

class Clock {
    constructor(timeDiv, alarmDiv, alarmTime) {
        this.timeDiv = timeDiv; // div to display time
        this.alarmDiv = alarmDiv; // div to display alarm
        this.alarmTime = alarmTime; // time to set alarm
        this.alarmAudio = document.querySelector(this.alarmDiv + " #alarm_audio"); // audio element to play alarm

        // set time on initial load
        let tim = document.querySelector(this.timeDiv);
        let t = new Date();
        let time = t.toLocaleTimeString([], {
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
        });
        tim.innerHTML = time;

        // set alarm on initial load
        this.setAlarm();

        // update time every second
        setInterval(this.updateTime.bind(this), 1000);
    }

    updateTime() {
        let tim = document.querySelector(this.timeDiv);
        let t = new Date();
        let time = t.toLocaleTimeString([], {
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
        });
        tim.innerHTML = time;

        if (time == this.alarmTime) {
            this.playAlarm();
        }
    }

    setAlarm() {
        const alarm = document.querySelector(this.alarmDiv + " span");
        alarm.innerText = `Alarm (${this.alarmTime})`;
    }

    /**
     * Play alarm when the time matches the alarm time
     */
    playAlarm() {
        this.alarmAudio.currentTime = 0; // reset audio to start
        this.alarmAudio.muted = false; // unmute audio
        this.alarmAudio.volume = 0.5; // set volume
        this.alarmAudio.play(); // play audio

        document.querySelector(this.alarmDiv + " button").style.display = "block";
        document
            .querySelector(this.alarmDiv + " button")
            .addEventListener("click", () => this.turnOffAlarm(this.alarmAudio));
        document.body.style.background = "#38a4ef";
    }

    turnOffAlarm(alarmAudio) {
        alarmAudio.muted = true; // mute audio
        document.querySelector(this.alarmDiv + " button").style.display = "none";
        document.body.style.background = 'url("/bg.jpg")';
    }
}
Enter fullscreen mode Exit fullscreen mode

This is a simple class that gathers variables for the divs and time that will be used in the project. Once it has the variables, it then creates the clock and adds the current time which changes every second to implement a second-based digital clock.

It then sets the alarm based on the this.alarmTime variable sent to the constructor.

Finally, it implements the second change using setInterval. This will allow it to rerun the code once every second.

Based on the following code, it will check to see if it needs to play an alarm.

if (time == this.alarmTime) {
    this.playAlarm();
}
Enter fullscreen mode Exit fullscreen mode

If the time equals the value set by the user, it then runs the playAlarm method. The playAlarm method starts the music in the background and changes the background color. Once this is done, it adds a button so the user can turn off the alarm and the entire process starts again.

To initialize the Clock class, you simply need to add the following code to either your main JS file or your HTML if you are copying my code as it is:

new Clock('#time', '#alarm', '02:38:00 PM')
Enter fullscreen mode Exit fullscreen mode

Our Clock Styles

The clock styles are simple and just display a background image with large-format text for the clock itself.

body {
    font-family: 'Fjalla One', sans-serif;
    text-align:center;
    background-color:#000;
    position: relative;
    height:100vh;
    overflow:hidden;
    background-image:url('/bg.jpg');
    background-size:cover;
}

.main {
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%, -60%);
    width:100%;
    height:100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction:column;
    #time {
        color:#fff;
        text-shadow: 3px 3px 0px #6d6d6d;
        font-size:100px;
        margin: 1rem 0;
    }
    #alarm {
        color: rgba(255,255,255,.5);
        font-size:30px;
        button {
            background-color: transparent;
            border:1px solid #fff;
            color:#fff;
            padding:15px 20px;
            font-size:20px;
            cursor: pointer;
            width:250px;
            margin:20px auto;
            display:none;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

This will give you a simple clock with an alarm feature you can use on your website or as a simple alarm on your own local machine.

NOTE In order to use the audio element with modern browser policies, you must have user interaction. If you are using this as a personal alarm, you can simply "Allow Audio" in your site settings within your browser. If you are using this as a public alarm, you will need to add a button to the page that will allow the user to interact with the audio element.

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await