I'm using JavaScript to check the user's time every 600ms (so my code runs once a second, but the time is unlikely to shift due to deviation in the setInterval method). My code looks like this:
setCorrectingInterval(function(){
needs_run = false;
switch(date.getDay()) {
case 1:
if(date.getHours() == "8" && date.getMinutes() == "50" && date.getSeconds() == "0") {
next = array.ItemA;
needs_run = true;
}
break;
[abridged, all other ifs and cases are identical except the times and days]
}
if(needs_run == true) {
alert("foobar");
}
}
(setCorrectingInterval is a custom function designed to correct the deviation from setInterval as much as possible)
My issue is that I never get alert("foobar"). I've used console.log() and done some trial-and-error, what I've narrowed it down to is the date.getSeconds() == 0 call. I've tried using (date.getSeconds() <= "5" && date.getSeconds() >= "0"), to no avail. The desired outcome is that, in this case, at 8:50AM on Monday, I get an alert, once.
When I omit the date.getSeconds() call, it works fine and dandy.
My guess is that something with your setCorrectingInterval() function or the date variable is wrong. It works fine with new Date().
;window.setInterval(function(){
var tDate = new Date()
console.log(tDate.getDay(), tDate.getHours(), tDate.getMinutes(), tDate.getSeconds())
needs_run = false;
switch(tDate.getDay()){
case 1:
if(tDate.getHours() == "8" && tDate.getMinutes() == "50" && tDate.getSeconds() == "0"){
//next = array.ItemA;
needs_run = true;
}
break;
case 5:
//No need to compare to string
//if(date.getHours() == "13" && date.getMinutes() >= "50" && date.getSeconds() >= "0") {
if(tDate.getHours() == 13 && tDate.getMinutes() >= 50 && tDate.getSeconds() >= 0){
//next = array.ItemA;
needs_run = true;
}
break;
}
if(needs_run == true){
console.log('foorbar') //alerts can be bad.
}
}, 1000);
More than likely, date is not what you expect it to be. I suppose the following would be more appropriate for your case:
var date = new Date();
switch(date.getDay()) {
...
You commented:
setCorrectingInterval is a custom function designed to correct the
deviation from setInterval as much as possible
What does that even mean? What do you mean by "correct the deviation from setInterval"?
Related
I'm trying to create a greeting pop-up and make it appear for only 5 secs, but I don't really get how to make it work.
Thanks in advance!
Here's code:
function greeting(event){
if (time >= 6 && time <= 11 ){
goodMorning.style = 'display:initial'
} else if (time >= 13 && time <= 17){
goodDay.style = 'display:initial'
} else if (time >= 17 && time <= 22) {
goodEvening.style = 'display:initial'
} else {
welcome.style = 'display:initial'
}
};
No need for all that complicated work. Just use a setTimeout to execute a function after a specified number of miliseconds.
var goodEvening = document.getElementById("a");
setTimeout(function(){hide(goodEvening);}, 5000);
function hide(element){
element.style.display="none";
}
<p id="a">Good evening!</p>
jQuery approach:
setTimeout(function(){$('#a').hide();},5000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="a">Good evening!</p>
I'm trying to optimize my code with a better way to do this.
I have a variable "hour". I need to make flags like this:
if (hour == 0) {flag12AM = 'yes'}
else {flag12AM == 'no'}
if (hour == 0 || hour == 1) {flag1AM = 'yes'}
else {flag1AM == 'no'}
if (hour == 0 || hour == 1 || hour == 2) {flag2AM = 'yes'}
else {flag2AM == 'no'}
[...]
if (hour == 0 || hour == 1 [...] || hour == 23) {flag23PM = 'yes'}
else {flag23PM == 'no'}
Could I use a loop to do that? I'm using Pentaho, so, if there's any step that do this job, please, let me know.
Thanks!!
Maybe this will be useful for you:
var h = 20;
[...Array(24).fill().map((v, i) => i + 1)]
.forEach((v) =>
console.log([...Array(v).fill().map((h, i) => i)]
.reduce((result, currentValue) => result || (h == currentValue), false), v))
You can use a data grid step to generate all flag values and then look up the hour and retrieve all flags.
IIUC, using Modified Java Script Value step, you can calculate all the flags with a for loop and then assign and export the values to specific flag names
var flags = []
for (i=0; i<24; i++) {
flags[i] = hour <= i ? "yes" : "no"
}
var flag12AM = flags[0]
var flag1AM = flags[1]
var flag2AM = flags[2]
....
var flag23PM = flags[23]
Or use Scripting -> Formula step
New field: flag12AM
Formula: IF([hour]<=0;"yes";"no")
Value type: String
do the similar to all other fields.
I have been working on this javascript timer and can't understand why it doesnt stop when the hours, minutes and seconds are equal to zero.
Code:
var s= 18000;
var h= Math.floor(s/3600);
s-= h*3600;
var m= Math.floor(s/60);
s -= m*60;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
if(s == 0 ){
if(m == 0){
h=h-1;
s=59;
m=59;
if(h == 0){
clearInterval(counter);
}
} else {
m=m-1;
s=59;
}
//Do code for showing the number of seconds here
} else {
s = s - 1;
}
document.getElementById("timer").innerHTML=h+'hrs '+m+'min '+s+'secs ';
}
The problem I see here is that you'll decrement h variable by 1 when all time variables - and by time variables I mean h, m and s are set to zero:
if(s == 0 ) {
if(m == 0) {
h=h-1;
s=59;
m=59;
// more code goes here
So h will be -1 and the timer will never stop.
The best I can propose is to rewrite your timer completely, and use only seconds here. Every time the timer function gets invoked you check if s equals to zero - if it is, you stop the timer. Otherwise, you decrement s by 1. To update the inner HTML of #timer element you can recalculate the number of hours, minutes and seconds on the every invocation of timer method - this solution will be a lot more easier to understand and maintain than the chain of nested conditional statements.
The problem appears to be the logic in this section here...
if(s == 0 ){
if(m == 0){
h=h-1; // what if h is also 0 here?? this would set it negative
s=59;
m=59;
if(h == 0){
clearInterval(counter);
}
I think you should be doing your if(h==0) check sooner... before you decrement the values. So you might want to start your if else block with a if (s == 0 && m == 00 && h == 0) and use that to clear the interval. If everything is already zero, you don't want to change any more values.
I am doing a comparison on dates in javascript. In this case date1 is empty "" and I can see the same in firebug. As per the code below, the first alert shouldn't be called because date1 == "", but for some reason the alert alert(" This is called...."); is invoked. What is wrong here?
if(date1 != null || date1 != ""){
if( (date1 != null || date2 != "") && (date1 < date2)){
alert(" This is called....");
break;
}
else{
alert(" That is called....");
break;
}
}
The above if condition is inside a for loop, hence the break.
I think you mean to be using && instead of || in your first comparision to make sure that both conditions are true and I think you have typo where you're using date1 instead of date2 in the second test. Further, you can just use if (date1) to simultaenously rule out null and "" and undefined and 0 and NaN and any other falsey value.
I think you want something like this:
if (date1) {
if(date2 && date1 < date2) {
alert(" This is called....");
} else {
alert(" That is called....");
}
break;
}
If what you're really trying to do is make sure that date1 and date2 are legal numbers, then I'd suggest you do this:
if (typeof date1 == "number") {
if(typeof date2 == "number" && date1 < date2) {
alert(" This is called....");
} else {
alert(" That is called....");
}
break;
}
Or, if they're supposed to be Date objects, then you can test for that:
if (date1 instanceof Date) {
if(date2 instanceof Date && date1 < date2) {
alert(" This is called....");
} else {
alert(" That is called....");
}
break;
}
It looks correct to me. This statement evaluates to true because of the OR (||), since date1 is not null:
if(date1 != null || date1 != ""){
(it simplifies to if (true || false) { which is always true.
and the following statement evaluates to true as well because "" is not equal to null, and, presumably, date1 is less than date2:
if( (date1 != null || date2 != "") && (date1 < date2)){
I want to suggest you this syntax
if( (x==5) || (x==6) || (x==7) || (x==8) )
this is best answer for checking OR condition using JavaScript and JQuery.
date1 is empty ""
Look at this condition:
date1 != null || date1 != ""
date1 is != null, the second term (date1 != "") isn't even evaluated because the first one passes - and the whole expressions evaluates to true.
Furthermore this condition:
date1 != null || date2 != ""
is also met (see above) - did you mean date2 != null this time? Nevertheless your This is called is displayed. BTW break has no sense in this context.
Finally you might consider simply:
if(date1) {
Not 1:1 equivalent, but pretty close.
Maybe that's a case where you should think about readability of your code. Here is my interpretation of your code:
if(!isBlank(date1){
if(dateXIsSmallerThanDateY(date1, date2))
alert(" This is called....");
else
alert(" That is called....");
}
function isBlank(date) {
return date != null || date != "";
}
function dateXIsSmallerThanDateY(x,y) {
return (x != null || y != "") && (x < y);
}
do you see a problem in dateXIsSmallerThanDateY? I can see one. What is that supposed to mean: x != null || y != ""? Probably it should read y != null || y != "", which in turn can be shortend to !isBlank(y).
Additionally the isBlank function does not check for beeing blank. Look what it does: It thinks that your date is blank if it is either not null or if it is not an empty string. Ok, maybe that is hard to read, so reverse this method:
function isNotBlank(date) {
return date == null && date == "";
}
Positive comparisions are way easier to read. Do you see what is happening here? Can date be null and "" AT THE SAME TIME? No? Good. Than I guess you know what to do:
function isNotBlank(date) {
return date != null && date != "";
}
Or in reverse:
function isBlank(date) {
return date == null || date == "";
}
$(.dateselboxes) .change( function(){
var y; y=$("#year").val();
var m; m=$("#month").val();
var d;
// check leap year
var leapYear;
if(y%4==0)
{
if(y%100==0)
{
if(y%400==0) {leapYear=true;}
else {leapYear=false;}
}
else {leapYear=true;}
}
else {leapYear=false;}
// calculate the number of days
var dz;
if(m==1 || m=3 || m=5 || m=7 || m=8 || m=10 || m=12) {dz=31;}
else if(m==2)
{
if(leapYear==true) {dz=29;}
else {dz=28;}
}
else {dz=30;}
// remove last option a couple of times
switch(dz)
{
case 28:
for(i=0;i<3;i++)
{$("#day option:last").remove();}
break;
case 29:
for(i=0;i<2;i++)
{$("#day option:last").remove();}
break;
case 30:
$("#day option:last").remove();
break;
default:
var axaxax=0;
break;
}
});
Here you go, this code works (in Chrome, at least):
var opts = $('#day option').get();
$('#month, #year').change(function() {
var y = +$('#year').val(),
m = +$('#month').val(),
leap = y % 400 === 0 || y % 100 !== 0 && y % 4 === 0 ? true : false,
days = 30;
switch ( m ) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31; break;
case 2:
days = leap ? 29 : 28; break;
}
$('#day').empty().append( opts.slice(0, days) );
});
Live demo: http://jsfiddle.net/83yUF/
$(.dateselboxes)! This will not select anything, however $(".dateselboxes") will. The jQuery $ accepts a string as its argument representing the selector.
Asside from that your question has no explanation and loads of code, I haver no idea what is going on!
Where you are calculating the number of days by checking the month #, you have single = instead of ==.
Replace with:
if(m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12) {dz=31;}
The single = will assign the new value to your m variable and always evaluate to be true, so I assume you were seeing 31 in your day selector always. As a practice, I like to avoid this scenario by reversing the check. ie: if(0 == x) since you can't assign to 0 an accidental single = will result in a javascript error, making it easier to avoid the mistake.
The problem is with assigning (=) to variable m instead of comparing (==)
if(m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12) {dz=31;}
As a side note, you could rewrite some parts of your script.
leapYear var - this uses 2 statements to reduce it yet still keep it readable.
leapYear = (y%4==0);
if (leapYear && (y%100==0) && !(y%400==0))
leapYear=false;
to remove the last options (0-indexed)
{$("#day option:gt(" + dz + ")").remove();}