working with filenames and scheduled function calls in javascript - javascript

I have a couple questions about javascript:
Does javascript have the capability to identify a filename with a timestamp as a name?
Similar to the Perl code below utilizing the POSIX module?
my $filepath = sprintf("/path/to/file%s.JSON",strftime("%y%m%d",localtime));
this is just an example. I would like to find file in format yy/mm/dd/hh/min
For example say I want to find a file with the name 12_11_03_15:15.json how can I do this with javascript.
Say I create a function that I want to trigger every 15 minutes to read the file how is this possible with javascript? I looked at setInterval() but that won't work because it is dependent on when the browser is launched. Is it possible to schedule a function to execute every hh:00, hh:15, hh:30, hh:45?
Thank you very much in advance.

You can use the Date class to get information about the current time.
To schedule a function to run at a certain time, setInterval() is indeed the best choice. It seems like what you're really looking for is a way to find out when to start the first interval such that it will fall on a quarter-hour. For that, you should again use Date to get the current time and subtract it from the next quarter-hour; you can use the resulting value with setTimeout to time the start of the first interval.
Here's an example: http://jsfiddle.net/GSF6C/3/
var nextQuarterHour = new Date();
nextQuarterHour.setMilliseconds(0);
nextQuarterHour.setSeconds(0);
do {
nextQuarterHour.setMinutes(nextQuarterHour.getMinutes() + 1);
} while (nextQuarterHour.getMinutes() % 15)
var millisecondsToNextQuarterHour = nextQuarterHour.getTime() - Date.now();
document.write(millisecondsToNextQuarterHour);
setTimeout(function () {
alert("Ding!");
setInterval(function () { alert("Dong!"); }, 15 * 60 * 1000);
}, millisecondsToNextQuarterHour);
​
​

Related

update fullCalendar( ‘getDate’ ) regularly

I need to update a moment variable like
var moment = calendar.fullCalendar('getDate');
regularly by using setInterval function but that doesn't have any effect and the moment variable is always the same. Is there a method to have the current moment updated each X seconds ?
thanks,
Perhaps I've misunderstood, but it's not really clear why you want to use fullCalendar's getDate function. This will return the date currently selected in fullCalendar. Updating that every few seconds wouldn't be much use - it'll only change whenever the user selects a new date.
If you want to report the actual current time, you can do it easily using momentJS directly, something like this:
var m;
function currentTime() {
m = moment();
console.log(m.toISOString());
}
setInterval(currentTime, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Is there a way to watch times with moment.js and run a function when it does?

I'm new to moment.js and javascript and I couldn't seem to find anything in moment.js documentation or other questions here. I am comparing two different times, and would like to watch the time and run a function when Time A is equals to Time B.
so something like:
var a = TimeA
var b = TimeB
//watch the current time
when a === b {
//run a function
}
else {
//do nothing
}
There are many ways you can do this. But the most traditional way is to use an Interval Function as Badgy has pointed. Here is an working example for a 1 second interval:
var timeA = moment().add(10, 'seconds'); // 10 seconds from now
var tmr = setInterval(()=>{
var now = moment().unix();
var then = timeA.unix();
console.log(now, then)
if (now >= then) {
clearInterval(tmr);
console.log('Whatever you want to do');
}
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
I used .unix() method in moment.js because it returns the time in seconds. So it's better for comparison with the first time than a string like '2013-02-04T22:44:30.652Z' or the isSame() method because it uses milliseconds and can skip the exact moment. A second is a large enough time unit so it can be compared to the current time.
You could make a interval function and check every second if the times equal each other. Also throw a look at this it may help too.

Using Javascript I want to be able to run a particular task at a certain time

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.
There are several issues with your code, which various people have pointed out.
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).
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.
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!
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.
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 ==
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:
HTML 5.1 - 6.2.4 Named access on the Window object
Do DOM tree elements with ids become global variables?
Why don't we just use element IDs as identifiers in JavaScript?
I think you should use ">=" operator, because you don't know if it's gonna be EXACTLY that time.

Javascript: Storing the current time's timestamp value

Is there a way to store the current timestamp in a Javascript variable? The reason is I want to compare Javascript's current time value with a Django time variable, and whenever the time matches, it will send a popup notification.
I guess reloading the page maybe every 3 seconds or so would work, but that seems extremely inefficient.
I'm not sure exactly what you're trying to do here. It's not likely the times will ever match exactly unless you check every millisecond, but you can always check when the time is greater than the django variable, or within a certain range. This will check the time every three seconds.
var django = // Create a javascript date object from django timestamp here
var interval = setInterval(function(){checkTime()}, 3000);
function checkTime() {
var d = new Date();
if (d >= django) {
//Do something here
clearInterval(interval);
}
}

How to count up time in javascript (maybe with jquery)

On my app, I have a command:
#uptime = 'uprecords -s | awk '{ print $5 }'
that returns the current uptime from computer (using uptimed).
it returns something like 01:00:00 (hours, minutes, seconds) and I want to count up this time.
How do I do that? I tried some count up jquery plugins but none of them worked like I want
How do you guys count up?
Thanks in advance
edit
I think I wasn't clear enough
What I want is to catch this uptime from my server (already done it), and via javascript, make it dinamically, counting up this current uptime, so if the user got away from keyboard, by example, the uptime still increases
You can use setInterval:
var seconds = 2642; // uptime in seconds
var timer = setInterval(
function() {
seconds++;
}, 1000
);
Also, see this reference on JS time functions.
I've done something (ugly) like this:
function atualizarTimer() {
//span.uptimed is a string like 01:23:45
var time = $('span.uptimed').text();
var d = new Date();
times = time.split(':');
d.setHours(times[0]);
d.setMinutes(times[1]);
d.setSeconds(times[2]);
d.setSeconds(d.getSeconds()+1);
document.getElementById("uptimed").innerHTML = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
}

Categories

Resources