JavaScript Project Ideas: Alarm Clock
The setTimeout() function in JavaScript can create a straightforward alarm clock that plays a sound or displays a message at a particular time. It is a great starter among javascript project ideas and a handy source of javascript exercises for beginners. Read the code, try the live demo, then solve the practice exercises.
How the JavaScript Alarm Clock Works
The alarm clock is one of the best javascript project ideas for learning timers. You give the setAlarm() function the time you want, it uses new Date() to find the difference between the current time and the alarm time, and setTimeout() runs your code once that many milliseconds have passed. A playSound() function plays an MP3 file, and a displayMessage() function shows a message.
If you are searching for javascript exercises for beginners, javascript tasks for practice or quick js exercises you can finish in one sitting, this project fits all three. The sections below cover the code, how to run it, a live demo with sound, and javascript practice exercises with solutions.
What the finished project does
- Takes an alarm time in 24-hour format, such as
08:00:00. - Works out the delay in seconds and converts it to milliseconds for
setTimeout(). - Plays a sound and shows a message when the time arrives.
- Can be cancelled with
clearTimeout()and runs in the browser.
new Date('08:00:00') is an Invalid Date, so the time difference was NaN and the alarm never rang. The new version builds the alarm from today’s date and uses tomorrow if the time has passed. It also adds clearAlarm(), catches blocked audio, skips sound in Node.js (which has no Audio), and the HTML page now reads the time from the input instead of calling setAlarm() with no value.Step 1: The setAlarm() Function
The desired alarm time is an argument to the setAlarm() function. A helper turns the text into a Date, the difference from now is calculated in seconds, and setTimeout() sets the alarm to go off at the designated time. This is also a good javascript function exercise: small functions that each do one job.
let alarmTimer = null;
// Turn "HH:MM" or "HH:MM:SS" into the next Date at that time
function getAlarmDate(alarmTime) {
const [h, m, s = 0] = alarmTime.split(':').map(Number);
const alarm = new Date();
alarm.setHours(h, m, s, 0);
if (alarm <= new Date()) alarm.setDate(alarm.getDate() + 1); // already passed: use tomorrow
return alarm;
}
function setAlarm(alarmTime) {
clearAlarm(); // keep only one alarm at a time
const alarmDate = getAlarmDate(alarmTime);
if (isNaN(alarmDate)) {
console.log('Invalid time. Use the 24-hour format, e.g. "08:00:00".');
return;
}
const currentTime = new Date().toLocaleTimeString();
const timeDiff = (alarmDate - new Date()) / 1000; // difference in seconds
console.log('Current time: ' + currentTime);
console.log('Alarm time: ' + alarmDate.toLocaleTimeString());
console.log('Rings in ' + Math.round(timeDiff) + ' seconds');
alarmTimer = setTimeout(function () {
playSound(); // Play a sound
displayMessage('Wake up!'); // Display a message
}, timeDiff * 1000); // convert seconds to milliseconds
}
function clearAlarm() {
clearTimeout(alarmTimer);
alarmTimer = null;
}
function playSound() {
if (typeof Audio === 'undefined') return; // Node.js has no Audio
// Replace 'sound.mp3' with the path to your sound file
const audio = new Audio('sound.mp3');
audio.play().catch(function () {
console.log('The browser blocked the sound. Click the page once, then try again.');
});
}
function displayMessage(message) {
console.log(message);
}
// Example (24-hour format): setAlarm('08:00:00');
// Lets Node.js load the file with require()
if (typeof module !== 'undefined') module.exports = { setAlarm, clearAlarm };Replace sound.mp3 with the path to your own sound file in MP3 format. The message that appears when the alarm sounds can also be changed. The variables alarmTimer, timeDiff and alarmDate make a compact set of javascript variables exercises for beginners.
Step 2: Run the Alarm Clock
Paste the code into your browser’s developer console and call setAlarm() with a time a minute or two ahead, for example setAlarm('07:59:30') if it is 7:59 now. You can also run it with Node.js, which prints the message but cannot play the sound:
node -e "require('./alarm_clock.js').setAlarm('08:00:00')"For an alarm 30 seconds away, the output looks like this:
Current time: 7:59:30 AM
Alarm time: 8:00:00 AM
Rings in 30 seconds
Wake up!The sound only plays in a browser, and browsers usually block audio until you have clicked or tapped the page once. That is why the web page below starts the alarm from a button.
Step 3: HTML Code with JS
If you want to view the project in the browser, use this HTML. It loads alarm_clock.js, reads the time from the time picker and shows the alarm status with textContent.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Alarm Clock</title>
</head>
<body>
<h1>Alarm Clock</h1>
<p>Set the alarm time:</p>
<input type="time" id="alarmTimeInput">
<button id="setBtn">Set Alarm</button>
<button id="cancelBtn">Cancel</button>
<p id="status"></p>
<script src="alarm_clock.js"></script>
<script>
const status = document.getElementById('status');
document.getElementById('setBtn').addEventListener('click', () => {
const value = document.getElementById('alarmTimeInput').value; // "HH:MM"
if (!value) {
status.textContent = 'Pick a time first.';
return;
}
setAlarm(value);
status.textContent = 'Alarm set for ' + value;
});
document.getElementById('cancelBtn').addEventListener('click', () => {
clearAlarm();
status.textContent = 'Alarm cancelled.';
});
</script>
</body>
</html>Live Demo: Alarm Clock in Action
This demo uses the same setTimeout() logic as the code above, with a live clock and a built-in beep instead of an MP3 file. Pick a time, or press Ring in 10 seconds to test it right away. Keep this tab open: browsers can delay timers in background tabs.
How to Turn This JavaScript Project into a Portfolio Piece
A working alarm is a good start, but how you present it matters just as much. Hiring managers look for evidence that you can finish a project and explain your decisions.
- Publish the code on GitHub with a README that explains what it does and how to run it.
- Host the live demo on GitHub Pages and link it from your portfolio.
- Explain your choices: why the alarm uses tomorrow’s date when the time has passed, and how autoplay rules affect the sound.
- Add tests for known inputs, such as an alarm at 23:59 or a time that has already passed.
Ideas to extend the alarm clock
- A snooze button that adds 5 minutes.
- Several alarms with labels, saved in
localStorage. - Desktop notifications with the Notification API.
- Repeat on selected days and a choice of ringtones.
JavaScript Exercises and Solutions Based on the Alarm Clock
The alarm clock is a great source of javascript exercises because every part practices a core idea. If you want javascript practice exercises with solutions, try each task yourself first, then open the solution to compare. These js exercises build on each other, from variables to functions to timers.
Javascript variables exercises and function exercises
Begin with exercise 1 (variables) and exercise 2 (functions). They are classic javascript exercises for beginners and take only a few minutes each.
1. Variables: greet by the hour
A javascript variables exercise: store the current hour in a variable and print a greeting.
const hour = new Date().getHours();
const greeting = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening';
console.log(greeting);2. Function: format seconds as mm:ss
A javascript function exercise: turn a number of seconds into a clock-style string.
function formatTime(totalSeconds) {
const m = String(Math.floor(totalSeconds / 60)).padStart(2, '0');
const s = String(totalSeconds % 60).padStart(2, '0');
return m + ':' + s;
}
console.log(formatTime(125)); // 02:053. Task: a 5-second countdown
One of the best javascript tasks for practice with timers: count down with setInterval and stop with clearInterval.
let n = 5;
const id = setInterval(() => {
console.log(n);
if (--n < 0) {
clearInterval(id);
console.log('Time is up!');
}
}, 1000);
// 5 4 3 2 1 0 Time is up!4. Challenge: add a snooze button
A js exercise with dates: return a new alarm time that is 5 minutes later.
function snooze(alarmDate, minutes = 5) {
return new Date(alarmDate.getTime() + minutes * 60000);
}
console.log(snooze(new Date('2026-01-01T08:00:00')).toLocaleTimeString()); // 8:05:00 AM5. Challenge: seconds until a time
Return how many seconds are left until a given HH:MM, today or tomorrow.
function secondsUntil(time) {
const [h, m] = time.split(':').map(Number);
const target = new Date();
target.setHours(h, m, 0, 0);
if (target <= new Date()) target.setDate(target.getDate() + 1);
return Math.round((target - new Date()) / 1000);
}
console.log(secondsUntil('23:59')); // seconds left until 23:59Looking for more javascript exercises and solutions? Browse our JavaScript projects and the free PDF practice sets.
Frequently Asked Questions About the JavaScript Alarm Clock
How do you make an alarm clock in JavaScript?
Read the alarm time, work out how many milliseconds are left until that time, and call setTimeout() with that delay. When the timer fires, play a sound with new Audio() and show a message.
Why is my JavaScript alarm sound not playing?
Browsers block audio until the visitor interacts with the page. Start the alarm from a button click, and make sure the path to your sound file is correct.
Does setTimeout() still work in a background tab or when the computer sleeps?
Browsers can delay timers in background tabs, and a sleeping computer pauses them. For a reliable alarm, check the real time with Date on a short interval, or use notifications and a service worker.
What is the difference between setTimeout() and setInterval()?
setTimeout() runs a function once after a delay. setInterval() runs it repeatedly until you stop it with clearInterval().
What can you do with JavaScript?
JavaScript builds interactive websites, web apps, browser games, server applications with Node.js, mobile apps and small tools such as an alarm clock.
How long does it take to learn JavaScript?
Most beginners learn the basics (variables, functions, loops, arrays) in a few weeks of regular practice, and become comfortable building projects after a few months.
Is JavaScript for beginners, and how hard is it?
Yes. You see results instantly in the browser, and the basics are easy. Asynchronous code and timers take more practice, so start with small javascript exercises for beginners like this alarm clock.
JavaScript FAQ in Turkish, Spanish, German and Arabic
Many learners search for JavaScript project ideas in their own language, so here are short answers to the most common questions.
Türkçe: JavaScript projeleri
JavaScript ile neler yapılabilir?
JavaScript ile web siteleri, mobil uygulamalar, oyunlar, Node.js ile sunucu uygulamaları ve çalar saat gibi küçük araçlar geliştirebilirsiniz.
JavaScript öğrenmek ne kadar sürer?
Temel konuları öğrenmek genellikle birkaç hafta, rahatça proje geliştirmek ise birkaç ay düzenli pratik gerektirir.
JavaScript hangi program?
JavaScript bir programlama dilidir. Tarayıcıda veya Node.js ile çalışır; kod yazmak için Visual Studio Code gibi bir editör yeterlidir.
JavaScript neden popüler?
Her tarayıcıda çalıştığı, öğrenmesi kolay olduğu ve hem ön yüzde hem arka yüzde kullanılabildiği için popülerdir.
Español: proyectos en JavaScript
¿Qué proyectos se pueden hacer con JavaScript?
Calculadoras, carritos de compra, relojes despertadores, juegos, aplicaciones del clima y mucho más.
¿Qué es un proyecto en JavaScript?
Es un programa o página web escrito con JavaScript que combina variables, funciones y temporizadores para resolver un problema concreto.
¿Cómo empezar un proyecto de JavaScript?
Crea un archivo .js, escribe una función pequeña como setAlarm() y ejecútala en la consola del navegador.
¿Qué programas se han hecho con JavaScript?
Sitios web, aplicaciones web, juegos de navegador, servidores con Node.js y aplicaciones de escritorio con Electron.
Deutsch: JavaScript lernen
Wird JavaScript noch benötigt?
Ja. JavaScript ist die Standardsprache des Webs, läuft in jedem Browser und wird mit Node.js auch auf Servern breit eingesetzt.
Was kann man alles mit JavaScript machen?
Websites, Web-Apps, Spiele, Server-Anwendungen, mobile Apps und kleine Tools wie einen Wecker.
Ist JavaScript für Anfänger?
Ja. Man sieht Ergebnisse sofort im Browser, und kleine Projekte erleichtern den Einstieg.
Wie schwierig ist JavaScript?
Die Grundlagen sind leicht zu lernen. Fortgeschrittene Themen wie asynchrone Programmierung brauchen mehr Übung.
العربية: مشاريع جافا سكريبت
تبحث عن مشاريع جافا سكريبت للمبتدئين؟ مشروع المنبه هذا مثال بسيط على مشروع جافا سكريبت يمكنك تجربته مباشرة وتعديل شيفرته. يمكنك أيضاً البحث عن مشاريع جافا سكريبت جاهزة pdf للحصول على شروحات مكتوبة، أو البحث عن مشروع جافا سكريبت github للعثور على شيفرات مفتوحة المصدر.
لست بحاجة إلى جافا سكريبت تحميل أو تحميل جافا سكريبت للاندرويد، فهي تعمل داخل المتصفح مباشرة، ويكفي تطبيق محرر أكواد إذا أردت الكتابة من الهاتف. أما تفعيل جافا سكريبت على الهاتف فيتم من إعدادات المتصفح إذا كانت معطّلة. وللتوسع جرّب مشاريع جافا للمبتدئين، مع ملاحظة أن جافا وجافا سكريبت لغتان مختلفتان.
Keep Building with JavaScript
You built an alarm clock with setTimeout(), fixed the invalid date problem, added a cancel option and practiced with javascript exercises and solutions. Small javascript project ideas like this one are the fastest way to learn, and with a README and a live demo they make a solid portfolio addition.
