How setInterval runs asynchronously

Viewed 1048

I have a setInterval function that runs async code that calls the server:

setInterval(()=> {
    //run AJAX function here
}, 5000);

If the server doesn't get a response within 5 seconds most probably it will run set Interval again which will then make multiple requests on the same endpoint, is there a way that the setInterval only starts its next 5 second execution after the AJAX function returns a response?

2 Answers

what you want to do is to use setTimeout when ever you get a response

here is some pseudo code

const doAjaxWithDelay = (delay)=>{
  setTimeout(()=>{
    $.ajax({
    ...
    }).done(()=>{
    // do your staff 
      doAjaxWithDelay(5000)
    })
  },delay)
}
doAjaxWithDelay(0);

Use setTimeout instead

function myTimer = () => {
  setTimeout(()=> {
    //run AJAX function here
    ajaxFunc();
  }, 5000);

function ajaxFunc() {
  //case success
    //do something
  // case failure
    // do something
  // finally
    myTimer();
}

myTimer()
Related