Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How setInterval runs asynchronously

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?

like image 356
The Bassman Avatar asked Mar 07 '26 02:03

The Bassman


1 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);
like image 96
Amit Wagner Avatar answered Mar 08 '26 14:03

Amit Wagner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!