Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
Javascript API polling

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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());

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!