I'm trying to make a script that will notify you if someone gets inline on Whatsapp web and I have this script:
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
// I want it to repeat onlineCheck() after 1 second
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + "Notification sent");
}
}
}
and I want to replace // I don't know what to put here with something that will run the function onlineCheck()
how should I do that
I first had this script:
var onlineCheck1 = window.setInterval(function(){
var x = document.querySelector('[title="online"]');
var name = $('#main>header>div.chat-body>div.chat-main>.chat-title>span').text()
var d = new Date();
if (x == null) {
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + name + " " + "was" + " " + "offline");
} else {
if (x.innerText === "online") {
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + name + " " + "was" + " " + "////online///");
} else {
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + name + " " + "was" + " " + "offline");
}
} ,1000);
but I want it to not do any thing with console log I just want it to repeat itself till it finds the element with the title="online"
Note: I'm using chrome's console to run the script and you can try it yourself if you want.
Invoke the function itself. This is called Recursion. You must be careful to prevent onlineCheck()calls itself infinitely
function onlineCheck()
{
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null)
{
onlineCheck();
}
else
{
if (y.innerText === 'online')
{
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
You can simply call the function as below
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
onlineCheck();
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
You need recursion technique.
While using this technique, the recursive function should need a termination condition to end the process (otherwise the process will infinitely iterates which will eventually cause Maximum call stack size exceeded error)
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
// Be sure to add a termination condition
onlineCheck()
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
As others have pointed out, you could just call the function directly: onlineCheck();. However, the loop condition (document.querySelector('[title="online"]') != null) won't have changed if you do that, so it'll go into an infinite loop/recursion.
Here's another way:
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
setTimeout(onlineCheck, 10);
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
This re-schedules onlineCheck to be called after 10 milliseconds, giving the page a chance to update before checking again. You may want to increase this number to, say, 1000; this way it'll check once every second instead of spinning in place, going "are we done yet? how about now? how about now? and now? now? now?".
Related
I have a nested array inside a list like the following:
{total_results, page, results [id, species_guess, observed_on_details {date, week, month, hour, year}]}
I am trying to get just the id, species_guess, and date using forEach.
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + data.results.id +
" - " + data.results.species_guess +
' (' + data.results.observed_on_details.date + ')')
);
}
This is saying " Cannot read property 'date' of undefined ". I have tried using a for loop like this and it worked just fine.
for (let i = 0; i < data.results.length; i++) {
console.log('#' + data.results[i].id + " - " + data.results[i].species_guess + ' (' + data.results[i].observed_on_details.date + ')');
}
Can anyone tell me where am I doing wrong here, sorry I am still new at this language.
you should use foreach as follow
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + element.id +
" - " + element.species_guess +
' (' + element.observed_on_details.date + ')')
);
}
Instead of
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + data.results.id +
" - " + data.results.species_guess +
' (' + data.results.observed_on_details.date + ')')
);
}
Replace "data.results" with "element"
function observationSummary2(data) {
data.results.forEach(element =>
console.log('#' + element.id +
" - " + element.species_guess +
' (' + element.observed_on_details.date + ')')
);
}
More info about "forEach()" here:
https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
This question already has answers here:
How to get next seven days from X and format in JS
(6 answers)
next 7 days in drop-down list [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to create a dropdown list that shows 14 days in the future via JS.
Right now it is showing only 7 days but with duplicates.
What is wrong?
screenshot dropdown
function createDates() {
$("#DT").find('option').remove().end().append('<option value="" selected>~#SELECT_DT~</option>');
var counter = 0;
var index = 1;
console.log(holidays);
while (counter < 14) {
var date = new Date();
date.setDate(date.getDate() + index);
var day = date.getDay();
var month = date.getMonth() + 1;
var isWeekend = (day == 6) || (day == 0);
var checkTime1 = getTimeOfDate(date.getFullYear(), month, date.getDate());
var isFound = false;
var selected = "";
if (index == ~(IF(#DT<>'',#DT,0))~) {
selected = 'selected="selected"';
}
if (!isWeekend) {
if (holidays.length > 0) {
$.each(holidays, function(key, obj) {
var hDay = new Date(obj.DT);
var checkTime2 = getTimeOfDate(hDay.getFullYear(), hDay.getMonth() + 1, hDay.getDate());
if (checkTime1 == checkTime2) {
isFound = true;
}
});
} else {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
if (!isFound) {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
}
index++;
}
}
The second if block should come under the first, also set isFound to false in the beginning:
if (!isWeekend) {
isFound = false;
if (holidays.length > 0) {
$.each(holidays, function(key, obj) {
var hDay = new Date(obj.DT);
var checkTime2 = getTimeOfDate(hDay.getFullYear(), hDay.getMonth() + 1, hDay.getDate());
if (checkTime1 == checkTime2) {
isFound = true;
}
});
if (!isFound) {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
} else {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
}
I want to prepend this variable "logText" and make it fade in at the same time.
var logText = today + ":" + " " + document.getElementById("textBox").value + '<br>\n';
$("#logContent").prepend(logText);
Here is what I got but it doesn't work.
var logText = today + ":" + " " + document.getElementById("textBox").value + '<br>\n';
$("#logContent").prepend($(logText).fadeIn('slow'));
$("<p>" + today + ": " + $("#textBox").val() + "</p>") // new DOM Node
.css("display", "none") // hide it
.prependTo("#logContent") // prepend it to #logContent
.fadeIn("slow"); // fade it in slowly
fiddle
$("#logContent").prepend(today + ": " + $("#textBox").val() + '<br>').fadeIn('slow');
I'm trying to perform a query in Android using: return query(selection, null, null, null), but cannot return the needed results when using multiple operators and parentheses. This is what I'm trying to do:
selection = "(KEY_VARIABLE > '5' AND KEY_VARIABLE2 = 'Yes') OR (KEY_VARIABLE < '5' AND KEY_VARIABLE2 = 'No')"
However, the query returns 0 results, because the query does not recognize the parentheses.
Is there a way to form a query in Android using multiple operators with an operator embedded within an operator statement?
UPDATE: There's no exception in logcat. Everything works fine, except for the embedded OR(AND) statements. Here's the code:
public Cursor getTierSchools() {
String range = "";
String range2 = "";
String range3 = "";
double score = LabValues.myscore;
double scoreplustwo = score + 2;
double scoreminustwo = score - 2;
double scoreplusfive = score + 5;
double scoreminusfive = score - 5;
double scoreminusone = score - 1;
range = "( " + KEY_SCHOOLSCORE + " > " + "'" + scoreplusfive + "'" + " AND " + KEY_SCHOOLSTATEBIAS + " = 'Yes' AND " + KEY_SCHOOLSTATELONG + " = " + "'" + LabValues.mystate + "'" + " )";
range2 = " OR " + "( " + KEY_SCHOOLSCORE + " > " + "'" + scoreminusone + "'" + " AND " + KEY_SCHOOLSTATEBIAS + " = 'Yes' AND " + KEY_SCHOOLSTATELONG + " != " + "'" + LabValues.mystate + "'" + " )";
range3 = " OR " + "( " + KEY_SCHOOLSCORE + " > " + "'" + scoreplustwo + "'" + " AND " + KEY_SCHOOLSTATEBIAS + " = 'No'" + " )";
String selection = range + range2 + range3;
return query(selection, null, null, sorting);
}
private Cursor query(String selection, String[] selectionArgs, String[] columns, String sortOrder) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(FTS_VIRTUAL_TABLE);
builder.setProjectionMap(mColumnMap);
Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
columns, selection, selectionArgs, null, null, sortOrder);
if (cursor == null) {
return null;
} else if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return cursor;
}
Basically, I'm trying to integrate AND statements within parentheses, similar to how you would form an equation like: (4+4)/8 = 1 IS NOT EQUAL TO 4+4/8 = 4.5 .
SOLUTION:
range = "(( " + KEY_SCHOOLSCORE + " > " + "'" + scoreplusfive + "'" + " AND " + KEY_SCHOOLSTATEBIAS + " = 'Yes' AND " + KEY_SCHOOLSTATELONG + " = " + "'" + LabValues.mystate + "'" + " )";
range2 = " OR " + "( " + KEY_SCHOOLSCORE + " > " + "'" + scoreminusone + "'" + " AND " + KEY_SCHOOLSTATEBIAS + " = 'Yes' AND " + KEY_SCHOOLSTATELONG + " != " + "'" + LabValues.mystate + "'" + " )";
range3 = " OR " + "( " + KEY_SCHOOLSCORE + " > " + "'" + scoreplustwo + "'" + " AND " + KEY_SCHOOLSTATEBIAS + " = 'No'" + " ))";
Hi I am trying to add 31 days to 'myDate' which is the current date. It is supposed to get the date add 31 days, then the convertDate function is supposed to translate it to something like 'Nov 31, 2012'. But it doesn't work. Does anyone know why?
Here is the primary function...
function process (infoarray) {
var myDate = new Date();
//var final = convertDate(myDate);
var length = infoarray.length;
var final_string;
for (var b = 0; b < length; b++) {
if (b == 0) {
if (infoarray[b][3] == 'After') {
final_string = '<b>' + infoarray[b][3] + ' ' + infoarray[b][1] + '</b><br/>' + infoarray[b][0] + '<br/>';
} else {
final_string = '<b>' + infoarray[b][1] + ' ' + infoarray[b][3] + ' ' + infoarray[b][2] + '</b><br/>' + infoarray[b][0] + '<br/>';
}
} else {
if (infoarray[b][3] == 'After') {
final_string = final_string + '<br/><b>' + infoarray[b][3] + ' ' + convertDate(myDate.setDate(myDate.getDate() + 31)) + '</b><br/>' + infoarray[b][0] + '<br/>';
} else {
final_string = final_string + '<br/><b>' + infoarray[b][1] + ' ' + infoarray[b][3] + ' ' + infoarray[b][2] + '</b><br/>' + infoarray[b][0] + '<br/>';
}
}
}
return final_string;
}
Here is the line i am focused on from the function above...
final_string = final_string + '<br/><b>' + infoarray[b][3] + ' ' + convertDate(myDate.setDate(myDate.getDate() + 31)) + '</b><br/>' + infoarray[b][0] + '<br/>';
Here is the convertDate function...
function convertDate(d) {
var day = d.getDate();
if (day < 10) {
day = '0' + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=['Jan','Feb','Mar','Apr','May','June','July','Aug','Sep','Oct', 'Nov','Dec'];
var currentMonth = months[month];
return (currentMonth + ' ' + day + ', ' + year);
}
myDate.setDate(...) modifies the value of the Date instance, but doesn't return anything.
You need to call setDate first, then pass the variable to your function.
Here.
First calculate then call
DEMO;
var myDate = new Date();
myDate.setDate(myDate.getDate()+31);
final_string = final_string + '<br/><b>' +
infoarray[b][3] + ' ' +
convertDate(myDate) + '</b><br/>' + infoarray[b][0] + '<br/>';
Or add it to the function:
.... convertDate(myDate,31) + ....
With
function convertDate(d,offset) {
if ( offset ) d.setDate(d.getDate()+offset);
var day = d.getDate();
if (day < 10) {
day = '0' + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=['Jan','Feb','Mar','Apr','May','June','July','Aug','Sep','Oct', 'Nov','Dec'];
var currentMonth = months[month];
return (currentMonth + ' ' + day + ', ' + year);
}
DEMO
By using setDate, you tell the Date object to set the day number to something between 32 and 62, which doesn't make much sense.
A good way to add 31 days would be to use getTime, which returns the number of mseconds ellapsed since 1st Jan 1970:
myDate.setTime( myDate.getTime()+31*24*60*60*1000 );
//31Days x 24 hours x 60 minutes x 60 seconds x 1000 msecs