Javascript: Storing the current time's timestamp value - javascript

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);
}
}

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>

Advice on this script

I have no knowledge of any sort of coding/ computer languages and need help using this script for a flash sale.
setInterval(function() {
var m = Math.floor((new Date).getTime()/1000);
if(m == '1476693000000') {
document.getElementsByTagName('a')[43].click();
}
else {
console.log("Script Activated…");
}
},10);
My question is what does this script 'really' do and is there any way to further improve it to enhance chances of buying the desired product?
This script has been described to be used for a flash sale on Mi India website and has been sourced from
http://trickweek.com/mi-rs-1-flash-sale-script-trick-buy-successfully-redmi-note3-mi4-rs-1/
It appears, that your script waits for a described time (2PM today) and once your system's time is 2PM it clicks on a specific link.
In this code, this line is
var m=Math.floor((new Date).getTime()/1000);
is unnecessary, erroneous and should be replaced by
var m=(new Date).getTime();
since it is later comparing m with an actual millisecond value.
Also, setInterval
It takes two parameters - callback handler and millisecond value.
It invokes the callback handler every 10 milliseconds.
The setInterval executes what is inside the function body every 10 milliseconds.
Var m gets the largest integer less than or equal to what is inside parenthesis.
Then goes the if condition to check if m equals 1476693000000 then the 43rd (starting from 0) element (tag) a gets found and clicked. If the if condition fails the else condition gets executed which prints to console log Script Activated….
The logic is simple. He is checking the flash sale time for every 10 milliseconds. Once the time reached, he is getting the "Add to cart" button on the page and clicking it dynamically.
I will explain you clearly.
For Example:
Mi mobiles flash sale is going to start on 17th October, 2016 at 2pm exactly. So, through javascript, he is checking the current time reached the expected time or not.
Usually, we cannot compare directly date with another date. So, we need to convert the date with time into most accurate time i.e, into milliseconds. so we can get the flash sale date's timestamp(time in milliseconds)..
var flashSaleTime = new Date("2016/10/17 02:00:00:000 PM").getTime();
Note: In Javascript, Default date format is YYYY/MM/DD and getTime() methods returns date in milliseconds.
So, We need to check the current time(in milliseconds) reached falshSaleTime, We need to click the Add To Cart button dynamically.
var flashSaleTime = new Date("2016/10/17 02:00:00:000 PM").getTime();
setInterval(function(){
var currentTime = Math.floor((new Date).getTime()/1000);
if(currentTime*1000 === flashSaleTime){
document.getElementsByTagName('a')[43].click();
}
},10);
here, setInterval function check the condition for every 10 milliseconds.
So, once current time reaches the target time, we are getting reference to the button and triggering click on the button.

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.

working with filenames and scheduled function calls in 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);
​
​

Multiple javascript timeouts - problem with live data fetching

I am building a real-time system which (with a use of websockets) updates a table with live data of different frequencies (can be 3 times per second, can be once every 2 seconds - dependant on the type of data).
I am currently struggling to find a way of letting the user know when a particular field has not been updated in the last 5 seconds. That is, if no new data is fetched, I shouldn't keep the old value there, but rather change it to '--' or something similar.
After a long way to the javascript, final function which updates fields looks like that (extremely simplified):
function changeValue(data){
var fieldId= data.fieldId;
var value = Math.round(data.value);
$('span#'+fieldId).text(value);
}
This function gets called each time a field needs to be changed. I've got between 2 and 40 different fields (dependant on the user) that are changed.
What is the best way of setting timers in order to change the values of the fields to '--' every 5 seconds, if no update has been made?
I would be really grateful for some tips,
Thanks,
Karol.
Since you want to indicate timeout on a per-field basis, you have two obvious options:
Have a global interval timer that ticks over fairly frequently and looks through all of your fields for a timeout.
Have independent timers for each field which just deal with that field.
I think on balance I prefer (1) to (2), because we're only dealing with one interval timer then and it makes the housekeeping simpler.
Since IDs in documents must be unique, we can use your field ID values as a key in a hash (an object) to store last updated times. This is kind of a spin on the previous answer but works on a per-field basis. So here's how we'd set those last updated times:
var lastUpdatedTimes = {};
function changeValue(data){
var fieldId= data.fieldId;
var value = Math.round(data.value);
$('span#'+fieldId).text(value);
lastUpdatedTimes[fieldId] = new Date().getTime();
}
Then you set up an interval timer to check each of them.
function checkFieldsForTimeout(){
var now = new Date.getTime();
// For each ID in lastUpdatedTimes, see if 'now minus
// last updated' is > 5000 and is so, set the field
// text to '--' and remove that entry from the last
// updated list with "delete lastUpdatedTimes[itemId]".
}
Should a timed-out field spring back to life, the "--" will be replaced by some real text again.
By deleting the last updated time from "lastUpdatedTimes" whenever we put "--" into a field, we make sure that the interval timer isn't wasting time processing fields that have already been timed out.
This answer was extended to handling multiple fields after the comment by #Andrew (please see also his answer).
Introduce a property updatedTime, which holds the last time the data was updated, in each data. A periodic timer checks updatedTime for all data and updates the text field if appropriate. The check has to be twice as often as the detection period. Your function changeValue() updates updatedTime and the text field.
function checkData() {
var now = new Date.getTime();
for "each data" {
if (now - data.updatedTime >= 5000) {
var fieldId = data.fieldId;
$('span#'+fieldId).text('--');
}
}
}
function changeValue(data) {
var fieldId = data.fieldId;
var value = Math.round(data.value);
$('span#'+fieldId).text(value);
data.updatedTime = new Date.getTime();
}
// Install periodic timer to check last updates:
setInterval(checkData, 5000 / 2); // interval = half the required detection period

Categories

Resources