anon
anon

Reputation:

How do I retry AJAX loop after n seconds for n times?

I have code in this structure.

If the error status is 429, I want to retry after 3 seconds, a maximum of 3 times.

$.ajax({
    url : 'url',
    type : 'PUT',
    data :  'data',   
    tryCount : 0,
    retryLimit : 3,
    success : function() {
        // do something
    },
    error : function(response, status, error ) {
        if (response.status == 429) {
            this.tryCount++;
            if (this.tryCount <= this.retryLimit) {
                $.ajax(this);
                return;
            } else {
                console.log('update failed!'); 
            }
        } else {
            // handle other errors
        }
    }


});

Where do I add the timeout? I keep getting an endless loop.

Upvotes: 0

Views: 762

Answers (2)

Jintor
Jintor

Reputation: 657

have you considered putting your $.ajax in function?

adding a counter variable combined with a setTimeout could do the trick.

counter = 0 ;
function ajaxfun () {
 $.ajax({
 //....
 error : function(response, status, error ) {
       counter ++;
       if ( counter < 3) { setTimeout(function(){ ajaxfun(); }, 3000); }
    },
 //...
 });
}

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370699

You just need to replace $.ajax(this) with a setTimeout wrapper around it:

$.ajax({
  url: 'https://httpstat.us/429?sleep=500',
  data: 'data',
  tryCount: 0,
  retryLimit: 3,
  success: function() {
    // do something
  },
  error: function(response, status, error) {
    if (response.status == 429) {
      this.tryCount++;
      if (this.tryCount <= this.retryLimit) {
        console.log('failure');
        setTimeout(() => {
          console.log('retrying');
          $.ajax(this);
        }, 3000);
        return;
      } else {
        console.log('update failed!');
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions