1

I know javascript is not the best way to go about this. I know that I would have to have the browser up and always running. I would normally do something with Python. This was a specific requests of me and i'm not very proficient with javascript. That being said.

I want the user to be able to set a time using inputs. Once these inputs have been set I want the browser to check for the time specified. Once the time occurs I want it to execute a command.

Her is what I have so far:

<html>
<body>

<p>Enter Time to start dashboard</p>
<p>Hour</p>
<input id="strthour">
<p>Minute</p>
<input id="strtmin">
<button onclick="setTime()">Submit</button>

<script>
var hr = 06; //default time of 6am to run
var mn = 00;

function setTime() {
  hr = strthour.value;
  mn = strtmin.value;
}

window.setInterval(function(){ // Set interval for checking
    alert(hr+mn);
    var date = new Date(); // Create a Date object to find out what time it is
    if(date.getHours() === hr && date.getMinutes() === mn && date.getSeconds() === 0){ // Check the time
        alert("it worked")
    }
}, 5000); // Repeat every 60000 milliseconds (1 minute)

</script>

</body>
</html>

I am able to change the global variables, but I am unable to get window.setInterval to recognize the changes. Any advice?

Here is a link to a JSFiddle I made.

Ryan113
  • 676
  • 1
  • 10
  • 27
  • I'm not sure what you mean by "I am unable to get window.setInterval to recognize the changes." Could you be more specific about what's going wrong? One problem I foresee is that you're checking if `date.getSeconds === 0` but `setInterval` is running every 5 seconds. – jered Feb 11 '16 at 22:01
  • When I use the setTime() function to change the global variables hr and mm window.setInterval does not recognize the changes. I want to be able to change the global variables using setTime() and have window.setInterval use their values to run a command at a certain time. – Ryan113 Feb 11 '16 at 22:05

5 Answers5

2

There are several issues with your code, which various people have pointed out.

  1. Walker Randolph Smith correctly notes that date.GetHours() and date.getMinutes() will both return numbers, while the values returned from strthour.value and strtmin.value will be strings. When JavaScript compares these two, it will always evaluate to false. To fix this, try running the user input through parseInt, as in hr = parseInt(strthour.value, 10);. The 10 is important because it tells parseInt to create a number of base 10 (you don't need to know what that means, just make sure to include the 10).

  2. Your need for the seconds to match is probably unnecessary, and does not match up with the interval you chose. TheMintyMate made this correction in their code snippet by simply removing the comparison for seconds. If you really need to make sure the seconds match up perfectly, pick an interval of less than 1000 milliseconds, so you know it is going to check at least once every second, guaranteeing that you will run the check on that 0th second of the desired time.

  3. You could run into some trouble with single digit minutes if you try to compare them as strings, rather than converting to numbers as recommended in point 1. The .getMinutes() method will return a single digit 0 for a time like 6:00, while your example is implicitly prompting the user to enter in two digits for that same time. Again, you can avoid this issue entirely by using parseInt as recommended in point #1.

I do have to throw in a plug for using Cron jobs for running tasks on a known schedule like this. I know you said the user requested JS in this case, so they may not apply for this specific situation. Since you didn't mention Cron jobs though, I have to include them here to make sure you and future readers are aware of them, because they are designed for exactly this situation of running a task on an automated schedule.

Good luck!

ClimbsRocks
  • 994
  • 13
  • 15
1

It's not because setInterval doesn't recognize the change, you actually don't modify the values.

If you open the javascript console on jsfiddle page you'll see "Uncaught ReferenceError: setTime is not defined".

It will work if you define you setTime like this:

window.setTime = function() {
  hr = strthour.value;
  mn = strtmin.value;
}

This is because JSFiddle doesn't run your code directly, but wraps into

<script type='text/javascript'>//<![CDATA[
window.onload=function(){ 
  ... // you code here }
}//]]>

Here is a modified JSFiddle which just "it worked" for me.

Update - some notes, as mentioned in other answers:

  • The use of '===' is also an issue, hr/mn are strings, so you need '==' or convert hr/mn to integers
  • Expression like strthour.value in setTime works in JSFiddle. I am not really sure why, but it works. In the "real world" it should be something like document.getElementById("strthour").value

Update 2 - why does strthour.value work (vs document.getElementById("strthour").value)?

This was actually a surprise for me, but it looks like all major browsers put all elements with id into window object. More than that, it is actually a part of the HTML standard (although it is not recommended to use this feature):

6.2.4 Named access on the Window object

window[name] Returns the indicated element or collection of elements.

As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().

References:

Community
  • 1
  • 1
Borys Serebrov
  • 15,636
  • 2
  • 38
  • 54
1
if(date.getHours() === hr && date.getMinutes() === mn && date.getSeconds() === 0){ // Check the time
        alert("it worked")
    }

This will compare a string to an int and always be false.

either perform parseInt(date.getHours()) or use ==

1

You are not correctly referring to the inputs, and you also have a syntax error with your alert. Below is my suggested fix (working):

<p>Enter Time to start dashboard</p>
<p>Hour</p>
<input id="strthour">
<p>Minute</p>
<input id="strtmin">
<button onclick="setTime()">Submit</button>
<script>
    var hr = 0;
    var mn = 0;

    function setTime() {
        hr = parseInt(document.getElementById("strthour").value);
        mn = parseInt(document.getElementById("strtmin").value);
        console.log("set time: "+hr+":"+mn);
    }

    setInterval(function(){
        var date = new Date();
        if(date.getHours() == hr && date.getMinutes() == mn){ // using == not ===
            alert("it worked");
        }
    }, 10000);
</script>

Note: You should also parseInt() the values to ensure they are valid numbers.

Matthew Spence
  • 986
  • 2
  • 9
  • 27
-1

I think you should use ">=" operator, because you don't know if it's gonna be EXACTLY that time.

MarioSumD
  • 1
  • 2