skip to Main Content

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.

2

Answers


  1. 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>
    Login or Signup to reply.
  2. 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); }
        },
     //...
     });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search