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

137
Views
how to do ajax call recursively, to check if service is available

I am trying to do ajax call recursively to check whether web service is available or not. Here is my code

function checkWebService() {
            console.log("function called")
            $.ajax({
                url:  "localhost:8085/login/checkWebServiceIsRunning",
                type: 'GET',
                success: (response) => {
                    console.log("success")
                },
                error: (jqXHR, textStatus, errorThrown) => {
                console.log("error")
                    setTimeout(() => {
                        checkWebService()
                    }, 1000)
                }
            })

        }

As my service is not running initially, the code from error block gets executed but after two or three times, the ajax call gets stuck, it neither goes in success nor in error.

Then I tried putting timeout in ajax code, so it gave timeout error, but even if the web service is available and server side code gets executed without any delay, ajax gives timeout issue.

Can someone help on what could be going wrong here.

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

0

You can use a while loop and async/await to get the response.

Also, you can add a variable count for the attempt to prevent infinite loop.

Furthermore, a wait function is added to delay each call to not utilize the program.

Note: errorCode:789 is just an example to catch the max attempt error. you can define your own.

const wait = ms => new Promise((resolve, reject) => setTimeout(resolve, ms));

async function checkWebService() {
  const MAX_ATTEMPT = 20;
  let attempt = 0;
  while (true) {
    try {
      attempt++;

      if (attempt > MAX_ATTEMPT) throw { errorCode: "789" };

      const response = await $.ajax({
        url: "localhost:8085/login/checkWebServiceIsRunning",
        type: "GET",
      });

      return response;
    } catch (err) {
      if (err.errorCode === "789") {
        throw new Error("Exceed Max. attempt.");
      }

      console.log(err);

      await wait(1000);

      continue;
    }
  }
}

checkWebService().then(console.log).catch(console.log);

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!