mystix
1/10/2015 - 4:04 AM

jQuery.ajax() retry

jQuery.ajax() retry

$.ajax({
    url: '/some/url',
    type: 'POST',
    data:  {
        some: 'data'
    },
    timeout: 1000,
    
    retryCount: 0,
    retryLimit: 3,
    retryTimeout: 10000,  // limits the total time retrying (in milliseconds)
    created : Date.now(), // when this request was created

    success: function(json) {
        // do something
    },

    error: function(xhr, textStatus, errorThrown) {
        if (textStatus == 'timeout') {
            this.retryCount++;

            if (
                (this.retryCount <= this.retryLimit) && 
                (Date.now() - this.created <  this.retryTimeout)
            ) {
                // retry
                $.ajax(this);

                return;
            }

            return;
        }

        if (xhr.status == 500) {
            // handle error
        } else {
            // handle error
        }
    }
});