Run function for 30 min - javascript

Here's what I want to do.
Execute a function : once, at some time of the day.
The function run for 30 minutes.
I've tried setTimeout but it doesn't fit my requirement because it run the function after X millisecond. Whereas I need the function to execute right away, at desired time for 30 minutes. Code as attached.
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var day = self.getDate();
var month_name=new Array(12);
month_name[0]="January"
month_name[1]="February"
month_name[2]="March"
month_name[3]="April"
month_name[4]="May"
month_name[5]="June"
month_name[6]="July"
month_name[7]="August"
month_name[8]="September"
month_name[9]="October"
month_name[10]="November"
month_name[11]="December"
var month = month_name[self.getMonth()];
var fullDate = month+' '+day+' '+hour+':'+minute;
function someFunction() {}
function closeFunction(){
noticeDiv.css('display', 'block');
mainDiv.css('display', 'none');
}
function executeFunction(targetDate){
if (fullDate == targetDate){
setTimeout ( closeFunction(), 180000 );
}else{
someFunction();
}
}
executeFunction(targetDate);

Use setInterval Function
Syntax-> var interval = setInterval(function(){function_name()},timeout In milliseconds);
To clear Interval or stop function we use ->clearInterval(interval);
HTML
<!-- Hide by default, show at target time -->
<div id="noticeDiv" style="display: none">
<h2>Registration Closed.</h2>
</div>
<!-- Show by default, hide at target time -->
<div id="mainDiv">
<h2>Registration Open.</h2>
</div>
jQuery
$(document).ready(function () {
var d = new Date();
var hour = d.getHours();
var minute = d.getMinutes();
var day = d.getDate();
var month_name = new Array(12);
month_name[0] = "January"
month_name[1] = "February"
month_name[2] = "March"
month_name[3] = "April"
month_name[4] = "May"
month_name[5] = "June"
month_name[6] = "July"
month_name[7] = "August"
month_name[8] = "September"
month_name[9] = "October"
month_name[10] = "November"
month_name[11] = "December"
var month = month_name[d.getMonth()];
var fullDate = month + ' ' + day + ' ' + hour + ':' + minute;
console.log(fullDate);
fulldate = 'May 3 17:1';
function executeFunction(targetDate) {
x = 0;
if (fulldate == targetDate) {
//set closing time of function 180000 = 30 min.It will hide div registration open and show registration closed div.
interval = setInterval(closeFunction, 180000);
} else {
openFunction();
}
}
function openFunction() {
console.log('Registration is now open')
}
function closeFunction() {
x++;
$('#mainDiv').append(x);
if (x == 1) {
$('#noticeDiv').show();
$('#mainDiv').hide();
clearInterval(interval);
}
}
// Execute time
executeFunction('May 3 17:1');
});
Working Demo http://jsfiddle.net/cse_tushar/8r5T8/

Related

Chrome Extension: calculate in miliseconds and click button after specific seconds

Well i am practising on Chrome Extension , i'm newbie on this.
Here is my code.
popup.html
<!doctype html>
<html>
<head>
<title>Laser Script</title>
<script type="text/javascript" src="popup.js"></script>
<style type="text/css">
h1 { font-size: 22px; }
.powered {
font-size: 14px;
margin-top: 8px;
}
</style>
</head>
<body>
<h1>Scheduled Click</h1>
<div id="contentWrapper">
<input type="text" id="duration" placeholder="Duration">
<input type="text" id="attack_date" placeholder="Day/Month/Year">
<input type="text" id="attack_time" placeholder="00:00:00">
<button id="schedule">Start Attack</button>
</div>
<div class="powered">Courtesy of <img src="justpark_logo.png" width="170px"></div>
</body>
</html>
popup.js
function initialise () {
// here im calculating the remind time in (mileseconds) that the button have to be pressed
var attack_timeInput = document.getElementById("attack_time");
var attack_timeParts = attack_timeInput.value.split(":");
var hours = parseInt(attack_timeParts[0],10);
var minutes = parseInt(attack_timeParts[1],10);
var seconds = parseInt(attack_timeParts[2],10);
var mileseconds = parseInt(attack_timeParts[3],10);
var attack_DateInput = document.getElementById("attack_date");
var attack_DateInputParts = attack_DateInput.value.split("/");
var day = parseInt(attack_DateInputParts[0],10);
var month = parseInt(attack_DateInputParts[1],10);
var year = parseInt(attack_DateInputParts[2],10);
var durationInput = document.getElementById("duration");
var durationParts = durationInput.value.split(":");
var hours2 = parseInt(durationParts[0],10)*3600000;
var minutes2 = parseInt(durationParts[1],10)*60000;
var seconds2 = parseInt(durationParts[2],10)*1000;
var duration_mile = hours2+minutes2+seconds2;
var now = new Date();
var new_now = now.getTime();
var full_attack_date = new Date(year, month-1, day, hours, minutes, seconds, mileseconds);
var new_full_attack_date = full_attack_date.getTime();
var delayInputValue = new_full_attack_date - new_now - duration_mile;
function scheduleClick () {
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
var codeString = 'var button = document.getElementById("troop_confirm_go"); setTimeout( function() { button.click(); },' + delayInputValue + ' )';
console.log(codeString);
chrome.tabs.executeScript({ code: 'console.log(document.getElementById("The attack will start ' + delayInputValue + ' miliseconds"))' });
chrome.tabs.executeScript({ code: codeString});
};
scheduleButton = document.getElementById("schedule");
scheduleButton.addEventListener('click', scheduleClick, true);
};
document.addEventListener('DOMContentLoaded', initialise, false);
So i have 3 inputs. I calculate the remind time until the button will be clicked. (it works)
But in this part
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
it diplays
The attack will start in NaN miliseconds.
and the button is pressed instantly.
I ckeched also this code:
var p = 1 ; //it's outside the function as the var delayInputValue
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'seconds';
and it displays :
The attack will start in 1 miliseconds.
So here is my question, why it can't read and work with the var delayInputValue but i can the var p?
Can i fix it somehow ?
Got it - the initialise() function is called when your DOM content is finished loading. At that point, the user has not entered information into the text fields, so they show as null or undefined. When the code starts running with this data it produces data as NaN since the calculations don't work.
In order for the code to run properly, you need to place the code dealing with data from those fields inside the scheduleClick() function, like so:
function initialise () {
function scheduleClick () {
var attack_timeInput = document.getElementById("attack_time");
var attack_timeParts = attack_timeInput.value.split(":");
var hours = parseInt(attack_timeParts[0],10);
var minutes = parseInt(attack_timeParts[1],10);
var seconds = parseInt(attack_timeParts[2],10);
//var mileseconds = parseInt(attack_timeParts[3],10);
var attack_DateInput = document.getElementById("attack_date");
var attack_DateInputParts = attack_DateInput.value.split("/");
var day = parseInt(attack_DateInputParts[0],10);
var month = parseInt(attack_DateInputParts[1],10);
var year = parseInt(attack_DateInputParts[2],10);
var durationInput = document.getElementById("duration");
var durationParts = durationInput.value.split(":");
var hours2 = parseInt(durationParts[0],10)*3600000;
var minutes2 = parseInt(durationParts[1],10)*60000;
var seconds2 = parseInt(durationParts[2],10)*1000;
var duration_mile = hours2+minutes2+seconds2;
var now = new Date();
var new_now = now.getTime();
var full_attack_date = new Date(year, month-1, day, hours, minutes, seconds);
var new_full_attack_date = full_attack_date.getTime();
var delayInputValue = new_full_attack_date - new_now - duration_mile;
document.getElementsByTagName("div")[0].innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
};
scheduleButton = document.getElementById("schedule");
scheduleButton.addEventListener('click', scheduleClick, true);
};
document.addEventListener('DOMContentLoaded', initialise, false);
Note that I also removed the miliseconds variable as the inputs I was using included hours, minutes and seconds only. You should also add some code to sanitise inputs to make sure they are in the format you want before calling the function.
Hope that helps

Make the output of a span the value of an input

Good day all, i am building a form that uses javascript to get a client's local time which is correctly displayed in span element. However i wish to make the output of the span element the value of an input field in order to pass same into mysql. I tried php like below, it rather displays the code.
$currenttradetime = "<span id='digital-clock'></span>";
$currenttt = $currenttradetime;
?>
<input type='hidden' name="time" value="<?php echo $currenttt; ?>"></span>'>
Then using html/php, it equally displays the span html codes rather than the time. How do i achieve this?
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
}, 1000);
The time is: <span id='digital-clock'></span>
<input type='text' value='<span id="digital-clock"></span>'>
Just use JavaScript to set the value of the input field like so:
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
document.getElementById('time').value = currentTime;
}, 1000);
<span id="digital-clock"></span>
<input id="time" />
Change
<input type='hidden' name="time" value="<?php echo $currenttt; ?>"></span>'>
to have an id too and do not set the html as value for the input field:
<input id='digital-clock-inputfield' type='hidden' name="time" value=""></span>'>
then change
document.getElementById("digital-clock").innerHTML = currentTime;
to set the value of the input field too:
document.getElementById("digital-clock").innerHTML = currentTime;
document.getElementById("digital-clock-inputfield").value = currentTime;

multiple alarm clock in javascript using dynamic generated input elements in javascript

I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var room = 0;
var i = 0;
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = document.getElementById('');
var minute = document.getElementById('');
var date = document.getElementById('');
}
</script>
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).
This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.
For an alarm project, I would recommend an interval of one second.
Example (not tested):
JavaScript
var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.
var ONE_SECOND = 1000; // miliseconds
var alarmClock = setInterval(function() {
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}, ONE_SECOND);
To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.
In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.
Hope this helps and good luck!
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.
EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var alarms = {};
var room = 0;
var i = 0;
setInterval(function() {
var current = new Date();
for (var nr in alarms) {
var alarm = alarms[nr];
console.log("checking alarm " + nr + " (" + alarm + ")");
if(current.getHours() == alarm.getHours()
&& current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
alert("ALERT\n"+alarm);
} else{
console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
}
}
}, 60000);
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
console.log(hour + ':' + minute + ' on ' + date);
var dateObj = new Date(date);
dateObj.setMinutes(minute);
dateObj.setHours(hour);
console.log(dateObj);
alarms[values] = dateObj;
}
</script>
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:
<script type="text/javascript">
var snd = new Audio("clock.mp3"); // buffers automatically when created
// Get
if (localStorage.getItem("test")) {
data = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
data = [];
}
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//since page reloads then we will just check it first for the data
function check() {
//current system values
console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
localStorage["test"] = JSON.stringify(data);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
{
check();
}
}
console.log(data);
var room = 1;
//var data = [];
var i = 0;
function GetDynamicTextBox(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var d = date.getDay();
return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
room++;
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
//get the current time and date
var today = new Date();
//current system values
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//first check that whether a same date present in the array or not then push it
var found = -1;
for(var i = 0; i < data.length; i++) {
if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
found = 0;
break;
}
}
//if value does not present then push it into the array
if(found == -1)
{
data.push({hours: hour, minutes: minute, dates: date});
//storing it into localstorage
localStorage.setItem("test", JSON.stringify(data));
}
else
{
alert("Same value Exists");
}
//console.log(data);
function check() {
//current system values
//console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
{
check();
}
}
}
</script>

Compare date and string with jquery

I'm trying to compare today date and the date from the string. They both has a string type. Why do I get "no!" ?
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" +(((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '16/10/2016';
if (String(datetodayvar) >= String(deadlinadate)) {
alert("yes!");
} else {
alert("no!");
}
});
Turn them both to Date objects instead of strings.
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '02/11/2016';
if(new Date(datetodayvar) >= new Date(deadlinadate)) {
alert("yes!");
} else {
alert("no!");
} });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you have your "date string" from 3 different input fields(dropdowns or whatever) don't input a string, but make the date format as follows.
var year = 2015;
var month = 2-1; // February
var day = 27;
var now = new Date(year, month, day);
That way, you don't have to worry about date notation, localisation, if you need to use a - a . or / or something else inbetween.
Also remember the month, is always -1 because it starts counting as 0(januari being 0, december being 11.
Also, keep mind of day light savings time. That might go hayward with your freshly minted date objects too by subtracting an hour.
The snippet below has all the things i'd use in a "simple" comparing mechanism.
jQuery(document).ready(function () {
var str = '';
for(var c=1;c<32;c++) {
str += '<option value="'+c+'">'+c+'</option>';
}
$('#day').html(str);
var str = '';
for(var c=0;c<12;c++) {
str += '<option value="'+c+'">'+(c+1)+'</option>';
}
$('#month').html(str);
var str = '';
for(var c=parseInt(new Date().getFullYear());c>1990;c--) {
str += '<option value="'+c+'">'+c+'</option>';
}
$('#year').html(str);
$('#istodaycheck').on('click',function() {
var day = $('#day').get(0);
var month = $('#month').get(0);
var year = $('#year').get(0);
var date = new Date(
year.options[year.selectedIndex].value,
month.options[month.selectedIndex].value,
day.options[day.selectedIndex].value);
date.correctDst();
$('#output').text(date.isToday() ? 'yes' : 'no');
});
});
/**
* Retrieve standard timezome offset
*/
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
/**
* Checks if date is in day lights savings
*/
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
/**
* corrects the unwanted substraction of an hour on fresh dates.
*/
Date.prototype.correctDst = function() {
if(!this.dst()) {
this.setHours(this.getHours()+1);
}
}
/**
* Returns a date instance without time components.
*/
Date.prototype.justDate = function() {
var date = new Date(this.getFullYear(),this.getMonth(),this.getDate());
date.correctDst();
return date;
}
/**
* Tests if given date is today.
*/
Date.prototype.isToday = function() {
// strip possible time part.
var testdate = this.justDate();
var datetodayvar = new Date().justDate();
return datetodayvar.getTime() == testdate.getTime()
}
#output {
background-color: #eee;
border: 1px solid pink;
display: block;
width: 100%;
height:200px;
text-align: center;
font-size:121pt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="day">
</select>
<select id="month">
</select>
<select id="year">
</select>
<button id="istodaycheck">Is this date today?</button>
<div id="output">
</div>
When comparing dates, always work with Date objects. The caveat with this is that when creating the objects, the provided date strings have to be in d/m/y or d-m-y format. Also note that today is not 16/10/2016.
jQuery(document).ready(function() {
var datetodayvar = new Date();
var deadlinadate = new Date('2/11/2016');
if (datetodayvar >= deadlinadate) {
console.log("yes!");
} else {
console.log("no!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First of all you are wrongly comparing two strings as if they were the numbers, when you do like this,
if(String(datetodayvar) >= String(deadlinadate)) { }
because if you want to compare strings you would have to
if(String(datetodayvar).equals(String(deadlinadate))){...
otherwise you compare the memory locations and not actual values.
Read more What is the difference between == vs equals() in Java?
This code will check whether the two string objects are greater than or equal to each other alphabetically, and not according to your actual requirement of date comparision. The functional code would be like this:
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '02/11/2016';
if(new Date(datetodayvar) >= new Date(deadlinadate)) {
console.log("yes!");
} else {
console.log("no!");
} });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Assuming date format as dd/mm/yyyy and that deadline >= today
var ar = '02/11/2016'.split('/').map(Number);
var valid = new Date(ar[2],ar[1]-1,ar[0]) >= new Date().setHours(0,0,0,0);
console.log(valid);

JS is refusing to loop a function [duplicate]

This question already has answers here:
Calling functions with setTimeout()
(6 answers)
Closed 7 years ago.
I am having a problem with a countdown. I have made the countdown however the JS to change the HTML refuses to loop. I have a setInterval and I have tried for, while and do loops but none work. I would really appreciate some help.
HTML:
<body>
<center>
<h1> Input the date and time you want to countdown to!</h1>
<form>
Second:<input id="seconds" type="number"><br>
Minute:<input id="minutes" type="number"><br>
Hour:<input id="hours" type="number"><br>
Day:<input id="days" type="number"><br>
Month:<input id="months" type="text"><br>
Year:<input id="years" type="number"><br>
</form>
<button onclick="start()">Calculate!</button>
<h1 id="yearsres"></h1>Years<br>
<h1 id="monthsres"></h1>Months<br>
<h1 id="daysres"></h1>Days<br>
<h1 id="hoursres"></h1>Hours<br>
<h1 id="minutesres"></h1>Minutes<br>
<h1 id="secondsres"></h1>Seconds<br>
</center>
</body>
JS:
function start() {
var myVar = setInterval(test(), 1000)
}
function test() {
console.log("hi");
}
function calculateseconds(sec) {
var year = document.getElementById("years").value;
var month = document.getElementById("months").value;
var day = document.getElementById("days").value;
var hour = document.getElementById("hours").value;
var minute = document.getElementById("minutes").value;
var second = document.getElementById("seconds").value;
var countdownto = new Date(month + " " + day + "," + " " + year + " " + hour + ":" + minute + ":" + second);
var epochto = countdownto.getTime()/1000.0;
var current = new Date();
var epochcurrent = current.getTime()/1000.0;
var epochcountdown = epochto - epochcurrent;
var t = parseInt(epochcountdown);
var years = 0;
var months = 0;
var days = 0;
var i = 1;
if(t>31556926){
years = parseInt(t/31556926); t = t-(years*31556926);
}
if(t>2629743){
months = parseInt(t/2629743); t = t-(months*2629743);
}
if(t>86400){
days = parseInt(t/86400); t = t-(days*86400);
}
var hours = parseInt(t/3600);
t = t-(hours*3600);
var minutes = parseInt(t/60);
t = t-(minutes*60);
document.getElementById("yearsres").innerHTML = years;
document.getElementById("monthsres").innerHTML = months;
document.getElementById("daysres").innerHTML = days;
document.getElementById("hoursres").innerHTML = hours;
document.getElementById("minutesres").innerHTML = minutes;
document.getElementById("secondsres").innerHTML = t;
}
By adding () to your test function you call it. setInterval method takes a reference to the function (name of the function) and interval in milliseconds.
It can be used like this:
function start() {
var myVar = setInterval(test, 1000);
}
Or like this:
function start() {
var myVar = setInterval(function() {
test();
}, 1000);
}
Also if you need to pass parameters to your function you can do it like this:
function start() {
var myVar = setInterval(test, 1000, "First param", "Second param");
}
Remove () from test()
somehow it will work
https://jsfiddle.net/alesmana/u30zmj3t/

Categories

Resources