XMLHttpRequest
is asynchronous by default (and a good practice, as calling it synchronously will block the browser). Therefore, the response from XMLHttpRequest.send()
should be handled asynchronously.
Calls to asynchronous function are handled traditionally with a callback function, using a pattern like this:
function myCallback (response) {
console.log('response from async function:', response);
}
function callAsyncFunction (myCallback) {
const async = new AsyncFunction();
async.oncompletion = function (response) {
myCallback(response);
}
Using that pattern, the checkPage()
function can be rewritten to use a callback function when it receives the desired 200 response code:
// callback to receive the 200 response
function handle200 (response) {
console.log('handle200 has received:', response);
}
function checkPage(callback) {
const xhr = new XMLHttpRequest(),
method = "GET",
url = "http://your-target-url-here";
// initialize a new GET request
xhr.open(method, url, true);
// respond to every readyState change
xhr.onreadystatechange = function () {
// ignore all readyStates other than "DONE"
if (xhr.readyState !== XMLHttpRequest.DONE) { return; }
// call the callback with status
if (xhr.status === 200) {
return callback(xhr.status);
}
// got something other than 200,
// re-initialize and send another GET request
xhr.open(method, url, true);
xhr.send();
}
// send the initial GET request
xhr.send();
}
// call checkPage once
checkPage(handle200);
References: