The alarm feature is malfunctioning

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:

http://codepen.io/kwikimart/pen/grkYoX

Answer №1

This particular issue arises from the following snippet of code

  function startTime() {
        var today = new Date();
       --> var h = today.getHours();
       --> var m = today.getMinutes();
       --> var s = today.getSeconds();

The problem lies in redeclaring the variables h, m, s within the startTime function, which are originally local to it.

During comparison with the globally scoped h, m, s variables, the values that were initially stored when the code first executes are referenced instead.

To resolve this issue, remove the var keyword for the variables defined inside the startTime function.

Insert console.log statements within the checkforAlarm method to observe that the previous timestamps are still being displayed.

Access Codepen Example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reducing Bootstrap Navigation Bar with a scrolling logo

Is there a way to make the fixed navbar shrink 50% when it starts scrolling? I've only come across text navbars, but I'm looking for one with a logo. Any suggestions would be greatly helpful. You can access the css and html from that link. ...

ESLint has detected a potential race condition where the `user.registered` variable could be reassigned using an outdated value. This issue is flagged by the `require-atomic-updates` rule

I have developed an asynchronous function which looks like this: let saveUser = async function(user){ await Database.saveUser(user); if (!user.active) { user.active = true; //storedUs ...

Creating a text or JSON file in React using Node.js

I am completely new to React and have been practicing by creating a basic website. So far, I can render data from a JSON file and read data entered into a text box to display it in the log file. However, I am struggling with writing to a file. Can anyone ...

Changing padding of a button causes surrounding elements to move?

Trying to make a button in CSS appear "pushed down" on :active, I decided to increase the padding-top by 2px and decrease padding-bottom by 2px. However, this adjustment seemed to affect the margins of other elements for some reason that eludes me. I am c ...

"Unraveling the Mystery: Leveraging jQuery to Unleash the

I'm working on a script that looks like this: $(document).on("click", ".passingID", function () { var ids = $(this).attr('data-id'); $("#idkl").val( ids ); $.ajax({ method: "POST", url: ...

What are some ways to capture and save the window width prior to launching my Nuxt application?

I am working on a Nuxt application where I need to display different components based on the window width and send a request to create a session with the device width as one of the header parameters. Here is my approach: In my store code: //index.js expor ...

Utilizing JavaScript to assign class names to dynamically created elements from objects

I specialize in javascript and am working on adding the CSS class .is-slideUp to each card__item element created from a data object, in order to achieve a sliding-up animation effect. Although the .is-slideUp class name appears in the console, it does not ...

Can anyone offer me advice on troubleshooting a failed Capifony deployment caused by a time out during the assetic:dump process?

$ cap deploy Unfortunately, the deployment process is failing and I am receiving the following error message: * executing "cd /var/www/site/prod/releases/20120831164520 && php app/console assetic:dump web --env=prod --no-debug" servers: ["site ...

Attempting to transfer various variables from several windows using AJAX

Is it possible to pass multiple variables from two different windows into the same PHP script? If not, what would be the best approach to take? Thank you. verifyemail.html <script type = "text/javascript" src = "js/js_functions.js"></script> ...

Successful execution occurring prior to beforeSend in a Cordova iOS application utilizing jQuery Ajax

After making some changes to the HTML of the login button, I encountered an issue where the alert was being triggered before the button's HTML had updated when testing on my iPhone using a Cordova-built app. Strangely, this problem did not occur when ...

What is the best way to save only the time in MySQL using Sequelize?

How can I properly store the Time HH:MM:SS using sequelize without encountering errors? I've tried using Time as a String and also as a Date Object, but I'm still facing issues. Here is the function I am using: const dateCollection = await booki ...

Having difficulties with hovering over a td that has a rowspan

I am encountering some challenges when attempting to hover over a td with rowspan in my HTML table. Despite searching for a solution, I have not been successful. I came across suggestions on forums that hinted at using JS/jQuery. Could someone please provi ...

Tips for submitting by simply choosing an option from a dropdown using jQuery?

Upon selecting a different week (uke) from the dropdown on the right or a trainer from the left dropdown above the schedule, it will automatically submit. There's no need to manually click the Submit(Vis) button. Is there a way to submit when just se ...

What could be causing my webpage to automatically refresh following a POST request in NodeJS?

Utilizing the express framework alongside NodeJS, I have encountered an issue where my client webpage refreshes after making a POST request that triggers a python script and returns a JSON object to the client. My dilemma lies in preventing this automatic ...

Is there a way to keep my fixed footer container from moving while zooming in and out on a webpage

Is there a way to prevent the bottom text from shifting when zoomed in or out on the page? The rest of the content remains stable, but due to using position:absolute for this section to stay at the bottom of another div (content), it causes movement. #con ...

A guide on changing the style of a Layout component in React

Currently, I am utilizing Next.js alongside Material-UI as the framework of choice. Within my project, there is a Layout component that encapsulates the content with Material-UI's <Container>. I desire to customize the style of the Layout compon ...

Converting Epoch timestamp to AM/PM format in a React render function

I am currently working on a personal project using React.js. I have successfully fetched an API, and one of the values returned is an Epoch timestamp. My goal is to display this timestamp in a human-readable format such as am/pm. The Epoch timestamp is dis ...

Conditional Matching with Javascript Regular Expressions

My strings are formatted like this: #WTK-56491650H #=> want to capture '56491650H' #M123456 #=> want to capture 'M123456' I am trying to extract everything after the # character, unless there is a dash. In that case, I onl ...

Choosing multiple items using ng-checked and ng-model in AngularJS

I am working with an Ionic application and encountering a minor issue, much like AngularJS. <ion-list class="list-inset subcategory" ng-repeat="item in shops"> <ion-checkbox class="item item-divider item-checkbox-right" ng-model="selectAll" ...

Stop users from repeating an action

We are encountering challenges with users repeating a specific action, even though we have measures in place to prevent it. Here is an overview of our current approach: Client side: The button becomes disabled after one click. Server side: We use a key h ...