With this loop I am checking if the destination page returns a 1 or nothing (blank page), but it always enters the two IFs , I don't understand it. It's wrong?
I have tested the destination page (const url) in the browser and if I am logged in it gives me 1, but otherwise it stays blank.
var i = 1;
var response = 0;
function myLoop () {
setTimeout(function () {
const Http = new XMLHttpRequest();
const url='url/get_session'; //Devuelve 1 o nada (página en blanco)
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
response = Http.responseText.replace(' ','');
if(response == '1'){ console.log('In: '+response); }
if(response != '1'){ console.log('Out: '+response);
//location.reload();
}
}
i++;
if (i < 10000000) { myLoop(); }
}, 5000)
}
myLoop();
The problem is that you check the value of the result before it reaches you, so it enters Out first and then In:
The property
readyState
value can be one of the following:open()
not yet called.open()
has been called.send()
has been called,headers
andstatus
they are reachable.responseText
may have partial data.So what you need is to check that the operation has completed before reading the responseText:
Although the simplest solution would be not to use
onreadystatechange
, but insteadonload
: