I have RestAPI endpoint providing simple response with single flag "needUpdate" true/false.
I am trying to write Javascript polling function which calls this endpoint and in case that needUpdate=true, it reloads whole web page.
var url = "https://www.example.com/api";
var needUpdate;
function poll(){
setTimeout(function(){
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function(e) {
if (this.status == 200) {
const myObj = this.response;
var needUpdate = myObj["needUpdate"];
console.log('needUpdate', needUpdate); // console
}
};
xhr.send();
if(needUpdate == true){
location.reload();
} else {
poll();
}
}, 3000);
}
var json = JSON.stringify(poll());
It calls API every 3 seconds as expected and also states proper value of needUpdate into console. But reload does not happen. It seems that needUpdate value is actualy undefined on the place where I tried to set a condition. Can you please help me?
move condition inside xhr.onload function
var url = "https://www.example.com/api";
var needUpdate;
function poll(){
setTimeout(function(){
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function(e) {
if (this.status == 200) {
const myObj = this.response;
var needUpdate = myObj["needUpdate"];
console.log('needUpdate', needUpdate); // console
if(needUpdate == true){
location.reload();
} else {
poll();
}
}
};
xhr.send();
}, 3000);
}
var json = JSON.stringify(poll());