Advice on this script - javascript

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.

Related

Multiple instances of countdown into html

I'm working a countdown with moment js.
This is the code:
https://telegra.ph/Codepen---Code-06-22 (CodePen)
I use this code to integrate into a programming table.
This is the table:
https://telegra.ph/Codepen---Code-06-22 (CodePen)
Now.
What I really want to achieve is:
First. Have a separate code for each row in my table.
(Perhaps one game is scheduled for 10:00, but another game could be scheduled for 10:15).
Second. Change the "if" condition so that the text displayed by my div changes if it has been more than 2 hours (which is what the games last approximately).
I am new to this so I appreciate any help.
Thanks-
You can achieve what you want with a two-step function:
The outer function will identify a DOM element into which the countdown will be written. The argument to this function must be a valid CSS selector.
The inner one will actually start the countdown to a given date. The argument(s) to this function will be passed on to the new Date() constructor called internally.
The below snippet is merely a demonstration of the mechanics needed for such a reusable function. My outer function will also provide a "stop" button to make the countdown stop. Within each outer function you will have access to the setInterval()-handle t. You can utilise this to program any other stop-mechanism for it (involving clearInterval(t)).
I was lazy when programming the time string inside the inner function: It will work correctly as long as the target event is within 31 days in the future from the current datetime. If you want to use it for a more general case you will have to put a little more effort into it ...
function countdown(DOMsel){
let trgEL=document.querySelector(DOMsel); // target DOM element
if (trgEL) return function(){
let trgDT=new Date(...arguments), // target Date object
btn=trgEL.nextElementSibling; // STOP button
let t=setInterval(function(){
let now=new Date()
if (trgDT-now<0) {
trgEL.innerHTML="<b>Game over, please insert coin!</b>";
clearInterval(t); // stop the current countdown
} else {
let str=new Date(trgDT - now).toJSON(); // timer string
trgEL.textContent=+str.substr(8,2)-1+':'+str.substr(11,8)
}
}, 1000);
btn.innerHTML='<button> stop </button>'; // build stop button ...
btn.onclick=function(){clearInterval(t);} // assign stop function to it
}
else return function(){console.log('target DOM element not found.');};
}
var now=new Date();
countdown('td:nth-child(3)')(now.setSeconds(now.getSeconds()+20));
countdown('tr:nth-child(5) td:nth-child(3)')(2020,5,26,20,5,27);
<table>
<tr><td>1</td><td>some</td><td>target1</td><td>next cell</td></tr>
<tr><td>2</td><td>table</td><td>with</td><td>various</td></tr>
<tr><td>3</td><td>cells</td><td>in</td><td>it.</td></tr>
<tr><td>4</td><td>d</td><td></td><td></td></tr>
<tr><td>5</td><td>e</td><td>target2</td><td></td></tr>
<tr><td>6</td><td>f</td><td></td><td></td></tr>
<tr><td>7</td><td>g</td><td></td><td></td></tr>
<tr><td>8</td><td>h</td><td></td><td></td></tr>
</table>
I used the new Date() constructor in the format (y,mon,d,min,sec) with mon being a 0-based index of months, therefore 5 indicates the 6th month: June. Interestingly, the d numbers work like normal calendar dates. But they may overshoot: if I had entered 31, then that would have become "1 July". Other formats are available, see here. Your input is always interpreted according to your local time zone, but the string we get from .toJSON() is always "Greenwich time". This seems weird at first, but is a great help when you are dealing with a global audience as they will all refer to the same clock automatically!
Edit:
I changed the target datetime of my first countdown such that it will always give you a 20 seconds window. After that a final message appears and he countdown stops.

How to get correct timestamp value in nodejs?

In my project my scheduling to post in social network sites using cron job,
timestamp value should end with zero instead of 1.
here is the node js code used:
var rule = new cron.RecurrenceRule();
rule.second = 0;
cron.scheduleJob(rule, function(){
var now = new Date();
var date = dateFormat(now, "dd-mm-yyyy, h:MM:ss TT");
console.log(Math.floor(new Date()/ 1000));
retrivepost(Math.floor(new Date()/ 1000).toString());
});
here is the timestamp value output log which i get in terminal
1517894101
1517894161
1517894221
1517894281
1517894341
1517894401
1517894461
1517894521
1517894581
1517894641
1517894701
1517894761
1517894821
1517894881
1517894941
1517895001
1517895061
1517895121
For me your code works just fine and logs timestamps ending with the zero second just like scheduled.
However, I think if your retrievepost() function depends on a timestamp being on the minute exactly you should round your date inside the .scheduleJob function to the nearest minute. A whole second later seems odd to me but imagine that you have some code just above that takes a while to compute. retrievepost() will fail then, even if you get it working right now.

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 compare datetime in javascript

I have been trying to get the code to work for more then 2 hours, then I tried this site, well there is alot of code here! I have used each of them. Some are in jQuery while some were pure JavaScript.
Here is two of the code that I have tried:
First code: This code was caught from this link: https://stackoverflow.com/a/2725097/1762944
var dateTimeStr = "17:10:03";
var user_time = DateTime.Parse( dateTimeStr );
var time_now = DateTime.Now;
if( time_now > user_time )
{
// your code...
}
Second code: This one is jQuery. It worked for the asker, and was marked as answer too. It works I have checked the fiddle provided by him! But when I tried the code, it didn't work either. Here:
function time_until() {
currentTime = Math.floor(jQuery.now() / 1000);
seconds = eventTime - currentTime;
if(second == 0){
//Stop voting
}
days = Math.floor(seconds / (60 * 60 * 24));
$('#time').html('seconds ' + seconds + '<br/>days ' + days);
}
I have tried to edit them both. But they don't work.
Reason why they work: The reason behind this all, is that what I want to do is,
I have a database table which is storing the time for users. I mean when they made an activity such like posting status updates!
I have created a timestamp. Which shows perfectly like this: few seconds ago.
Now what I want is, to update the time to 1 minute ago without reloading the page, like Facebook does. Or whatever the time is, to get updated to the next minute or hour or corresponding.
What I have tried is almost next to everything. But I guess the only issue with my codes is that when I place the DateTime.Now value from Database in it, it shows an error. The error is hidden so I have created an else statement like this:
if(seconds < 60) {
$("#jstime").html(seconds + "seconds..");
// else if minutes, if hours they are all written..and then an else
} else {
$("#jstime").html("Again an error, try again bud");
}
I have a setInterval which keeps on updating the id with the error text.
Here is the code that I am using.
<span id="timeval" title="#timeStamp">#TimeStamp</span></div>
<input type="hidden" id="time" value="9/23/2013 8:10:40 PM" />
<span>Real time: #TimeStamp</span><br>
<span id="update">Updated time: no update till now;</span><br>
<span id="jstime">Time</span>
The timeval is the real time that is being shown to the users, input is the time from where I get the value of the time on each post, the next span just shows the time to me, I mean I used this to check what was the time when the page was loaded, update is the span to show the updated time, jstime can also be used to show the updated time.
The problem is that you stored currentTime in the function you call every n seconds. As it gets looped it will everytime create a new current time.
Make it a global variable so you can loop through the function without creating the time new and use the old time instead.
Please go to link on stackoverflow and see my answer on how can we compare two dates along with the time in Javascript.

Categories

Resources