I have been struggling with a simple alarm application that I created using jQuery and Javascript. The issue lies in the alarm functionality not working as expected. Below is the relevant code snippet:
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
current_Time = h + ":" + m + ":" + s;
document.getElementById('txt').innerHTML =
current_Time;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function checkForAlarm() {
console.log("h :: " + h);
console.log("m :: " + m);
console.log("s :: " + s);
if (h == 17 && m == 52 && s == 16) {
console.log("play")
//var audio = new Audio('Prince.mp3');
audio.play();
}
else {
console.log("not");
}
}
window.setInterval(function(){
checkForAlarm()
}, 1000);
Upon closer inspection, I found that removing the m and s variables and letting the h variable equals h solves the problem, but if the application is launched before the specified time, the audio does not play. If anyone can provide assistance on this matter, it would be greatly appreciated. Please refer to the full CodePen for more details: