How to set timeout on $.ajax request and redo it if it takes too long?

前端 未结 4 1126
有刺的猬
有刺的猬 2021-01-20 16:26

Can someone show me a practical example on setting a timeout to my $.ajax request and redo the entire request if the first request is timed out, I\'ve read the docs and didn

4条回答
  •  野性不改
    2021-01-20 16:45

    a. You can maintain a queue of all the requests that you make.

    $.xhrQueue = [];
    

    b. Enqueue each request that you make

    $.ajaxSetup({
        beforeSend: function (e, xhr) {  
                $.xhrQueue .push(xhr);
            }
    });
    

    c. Poll for which requests completed vs timed-out

    setInterval(function(){
        $.each($.xhrQueue, function (xhr) {
           //check whether status is complete, 
           //with some try-catch you can know which were the timed-out/not-sent ones
    
        });
    }, 1000);
    

    Note: If not beforeSend, you can go via some other function through which you attempt to make an ajax call

提交回复
热议问题