LoginSignup
10
11

More than 5 years have passed since last update.

ajaxでリトライ処理

Last updated at Posted at 2018-02-23

ajaxでリトライ処理
done、failでの方法が見つからなかったので自分なりにかいてみました。
jQuery等の読み込み部分は省略します。
下記の実装だと、最初の通信を含め計4回通信を行って、
タイムアウト時間は1秒、2秒、4秒、8秒になっています。

retry.js

var time = 1000;
var request_cnt = 0;
const request = function(){
    $.ajax({
        url: 'htt://xxx.php',
        type: 'get',
        timeout: time,
        data: {
            //data
        }
    }).done(function (response){
        // 成功時の処理
    }).fail(function (jqXHR, textStatus){
        // リトライ処理
        if(textStatus === 'timeout' && request_cnt < 3){
            time = time*2;
            request_cnt++;
            return request();
        }
    });
}
request();

ajaxを触ったのはこれが初めてなので、もっといい方法がありましたら、ご教授いただけると幸いです。

10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11