Testing Internet connection at regular intervals - javascript

I want to check if a certain website is online every 3 seconds.
If the connection exists and the site is online, I want to show "Connected" alert every 3 seconds, but if there's no connection or the site is not online, I want to show "Not connected" alert, also every 3 seconds.
I tried this:
var myURL = "http://www.example.com/";
function testConnection(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() { alert("Connected!");}
xmlhttp.onerror = function() { alert("Not Connected"); }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
var tickingClock = setInterval(testConnection(myURL), 3000);
This, however, results in an alert only appearing once. What should I change in this snippet tp make it do what I want it to do?

You are calling the function, rather than putting a reference to the function in your setInterval statement. The proper method would be:
var tickingClock = setInterval(function() { testConnection(myURL); }, 3000);
setInterval accepts a function (or a string, but try to avoid using a string). Your code fires the testConnection method, then gives the return value as the argument to setInterval. But that return value is undefined, so the setInterval has nothing to do.

Related

Calling a Function once on load, then every interval using setTimeout

I have a JS script in a file which gets the timeout value from an inline script, which I do not have the ability to change, only the JS script.
The generated HTML looks something like this, which I cannot control:
<html>
<head>
<script="script-i-have-control-over.js"></script>
window.statusTimeout="3000";
</head>
So I have this JS function in the script-i-have-control-over.js:
function getStatus() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
if (response) {
var statusValue = JSON.parse(response.data);
document.getElementById('status').innerHTML = statusValue;
}
}
};
xhttp.open("GET","/index.php?api_status",true);
xhttp.send();
setTimeout(getStatus, window.statusTimeout);
};
getStatus();
This function only works after the first execution because window.statusTimeout is undefined on first execution, but then gets the value 3000 on second execution.
I think the problem is the getStatus() call at the end is executed on page load. Further, I want the first call of getStatus() to be able to get the value of window.statusTimeout, and the setTimeout only to fire after the the 3000ms, then every 3000ms.
Currently, getStatus function is executed twice on page load, fails the first time, works the second time then continues to work every 3000ms.
Where am I going wrong? To reiterate, I do not have control over the inline JS in the HTML. I need the AJAX to do its job ASAP on page load too.
The problem appears to be that getStatus is being called as soon as the script is read, which is before window.statusTimeout is set.
This will delay the first call to getStatus until the window's load event:
window.addEventListener('load', getStatus);
That may provide enough time for window.statusTimeout="3000"; to be evaluated.
Or you could simply change this line:
setTimeout(getStatus, window.statusTimeout);
to:
setTimeout(getStatus, window.statusTimeout || 3000);

Counting the inverter transition for its own function

I am writing a bot for google chrome in javascript and I have a problem, namely:
I check in intervale if the user has not disconnected. If he disconnected - skip it and open a new message. If not - I want to send specific messages in sequence. Unfortunately, but the repeating interval calls the same function over and over again, i.e. sendWelcomeMessage, when I want to stop this function after one interval and use another function.
I tried to bind a parameter to a function, but it does not work like I would like.
function message() {
var exists = document.getElementsByClassName("log-disconnected")[0].getAttribute("style");
var nextBtn = document.getElementsByClassName("o-new-talk")[0];
if (exists == "display: block;") {
console.log("Stranger disconnected");
nextBtn.click();
} else {
setTimeout(sendWelcomeMessage, 4000);
}
}
setInterval(message, 3000);

XMLHttprequest.send(null) is crashing my code

I'm currently writing a search function using JavaScript.
However, when I attempt to test my creation, I find that it stops about halfway through for no discernible reason.
Below is my code:
document.getElementById("test").innerHTML = "";
var Connect = new XMLHttpRequest();
Connect.open("GET", "xmlTest.xml", false);
document.getElementById("test").innerHTML = "1";
Connect.send(null);
document.getElementById("test").innerHTML = "2";
var docX = Connect.responseXML;
var linjer = docX.getElementsByTagName("linjer");
The first line is there to clear a potential error message from earlier in the code. Then I attempt to open up an XML file, as I need to read from it.
As you can see, I've entered two debug statements there; they will print 1 or 2 depending on how far I get in the code.
Using this, I've found that it stops exactly on the Connect.send(null); statement (as 1 gets printed, but 2 never does), but I can't figure out why. Google says that it might be that chrome can't access local files, but when I found a way to allow Chrome to do this, it still did not work.
What am I doing wrong?
This might be a synchronous issue that requires a response that your code simply is not getting.
Try using an async call instead:
Connect.open("GET", "xmlTest.xml", true);
Also make sure to setup proper callbacks since you'll be using async here now instead of synchronous code, like so:
// Global variable scope
var docX;
var linjer;
// Define your get function
getDoc = function(url, cbFunc) {
var Connect = new XMLHttpRequest();
// Perform actions after request is sent
// You'll insert your callback here
Connect.onreadystatechange = function() {
// 4 means request finished and response is ready
if ( Connect.readyState == 4 ) {
// Here is where you do the callback
cbFunc(Connect.responseXML);
}
};
// 'true' param means async, it is also the default
Connect.open('GET', url, true);
Connect.send();
}
// Define your callback function
callbackFunction = function(responseXML) {
// XML file can now be stored in the global variable
window.docX = responseXML;
window.linjer = window.docX.getElementsByTagName("linjer");
}
// And here is the call you make to do this
getDoc("xmlTest.xml", callbackFunction);
For better understanding of all of this, do some research on scope, closures, callbacks, and async.

AJAX call with common parameters gives always readyState = 1

I'm writing a ColdFusion application that fills with some HTML content some divs once the corresponding button is clicked.
What happens is that the readyState never goes up from the initial state of 1.
The fact that makes me crazy is that I used the same AJAX code in other modules that work fine.
I tried manually the code in my applet "___AJAX_load_translator.cfm" to see if works correctly (inputting a complete url with parameters and query string) and it works.
I put many alerts in these javascript functions to trace if the url was created correctly, the parameters were formatted correctly and so on. Everything seems fine. This is driving me crazy. The result is the same on FireFox and IE.
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else
if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("No AJAX support.");
return null;
}
}
function setOutput(divID){
if(httpObject.readyState == 4 && httpObject.status == 200){
document.getElementById(divID).innerHTML = httpObject.responseText;
} // else alert(httpObject.readyState + ' ' + httpObject.status);
}
function loadeditor(divID,CP,PP){
<CFOUTPUT>var CF_TOKENS = "CFID=#CFID#&CFTOKEN=#CFTOKEN#";</CFOUTPUT>
var operativeurl= "___AJAX_load_translator.cfm?"+CF_TOKENS+"&CP="+CP+"&PP="+PP;
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("POST", operativeurl, true);
httpObject.onreadystatechange = setOutput(divID);
httpObject.send(null);
}
}
I noticed that, putting an alert into the setOutput function, it displays a sudden readystate of 1. Then the browser statusbar shows the status of wait for a call to the server, that disappears quite immediately. It seems that the call is really done in that moment, and probably it is imho.
But it seems to me that after that readyness of the call (state 1) there is no more proceeding. It seems somehow blocked. Or, the function setOutput is deactivated. Maybe a second change to a state of 4 happens and this state is not registered by the callback ? In this case, why the DIV is not updated with the new content ?
Thanks for any help.
httpObject.onreadystatechange = setOutput(divID);
^^^^^^^
You're calling/executing your setouput function right then and there, and whatever the function returns becomes on the onreadystatechange callback "pointer".
Remove the (divID) portion, so you assign the function itself, not whatever it returns:
httpObject.onreadystatechange = setOutput;

jQuery event only every time interval

$(document).ready(function() {
$('#domain').change(function() {
//
});
});
The code inside the change function will basically send ajax request to run a PHP script. The #domain is a text input field. So basically what I want to do is to send ajax requests as user types in some text inside the text field (for example search suggestions).
However, I would like to set a time interval in order to lessen the load of PHP server. Because if jQuery sends AJAX request every time user adds another letter to the text field it would consume lots of bandwidth.
So I would like to set let's say 2 seconds as an interval. The AJAX request will be fired every time the user types a letter but with maximum frequency of 2 seconds.
How can I do that?
$(function() {
var timer = 0;
$("#domain").change(function() {
clearTimeout(timer);
timer = setTimeout(function(){
// Do stuff here
}, 2000);
});
});
$(document).ready(function() {
var ajaxQueue;
$('#domain').change(function() {
if(!ajaxQueue) {
ajaxQueue = setTimeout(function() {
/* your stuff */
ajaxQueue = null;
}, 2000);
}
});
});
What you really want to do is check how long since the last change event so you keep track of the number of milliseconds between events rather than make a call every 2 seconds.
$(document).ready(function() {
var lastreq = 0; //0 means there were never any requests sent
$('#domain').change(function() {
var d = new Date();
var currenttime = d.getTime(); //get the time of this change event
var interval = currenttime - lastreq; //how many milliseconds since the last request
if(interval >= 2000){ //more than 2 seconds
lastreq = currenttime; //set lastreq for next change event
//perform AJAX call
}
});
});
Off the top of my head without trying this in a browser. Something like this:
$('#domain').change(function() {
if (!this.sendToServer) { // some expando property I made up
var that = this;
this.sendToServer = setTimeout(function(that) {
// use "that" as a reference to your element that fired the onchange.
// Do your AJAX call here
that.sendToServer = undefined;
}, yourTimeoutTimeInMillis)
}
else {
clearTimeout(this.sendToServer);
}
});
two variables, charBuffer, sendFlag
Use a setTimeout to have a function be called every two seconds.
This function checks if the buffer has stuff in it.
If it does, it sends/empties the stuff and clears the sent flag (to false).
and It should also clear the timeout, and set it again
else it sets the flag (to true).
Everytime the user hits a key, store it in the buffer.
if the sent flag is clear (it's false), do nothing.
else (it's true) send/empty the stuff currently in the buffer and clear the flag (to false),
and It should also clear the timeout, and set it again
This will make it so that the first time you press a key, it is sent, and a minimum of 2 seconds must pass before it can send again.
Could use some tweaking, but i use this setup to do something similar.
I am coming across this problem more and more (the more i do UI ajax stuff) so i packaged this up into a plugin available here

Categories

Resources