How to cancel an ajax request or third party js request when no response after x time w/ abort()

StackOverflow https://stackoverflow.com/questions/21964045

Pergunta

Curious what are some of your solutions, elegantly, that deal with block js calls / ajax calls that take too long reaching out to third party sites for data/info.

Lately, I've been contending with some scripts/ajax requests in which the server is either down or not responding and literally blocks my page. They are suppose to be async.

So, I want to abort the call after x time.

var request = $.ajax({
    type: 'POST',
    url: 'someurl',
    success: function(result){}
});

then use: request.abort() if it takes too long.

But I am thinking I can use a deferred/promise here, with a timeout ability and call abort if my promise doesn't come back in say 1000ms.

Your thoughts?

My bad for not referring to the timeout attr of the ajax request. I didn't want to wrap the abort() in a setTimeout, but having the jQuery ajax api w/ timeout is what I need. I should have seen this. thanks all.

Foi útil?

Solução

Check the timeout option: http://api.jquery.com/jQuery.ajax/

var request = $.ajax({
    type: 'POST',
    url: 'someurl',
    timeout: 2000,
    success: function(result){},
    error: function(xhr, status, message) {
        if(status == "timeout") {
            alert("Request time out");
       }
   }
});

Outras dicas

One way can be using setTimeout

var abort_req = setTimeout(function () {
    request.abort();
}, 3000);
 //^ time in ms 

Possible duplicate of jQuery $.ajax timeout setting. JQuery AJAX has an optional timeout option that can be passed by milliseconds. You can process logic when the AJAX request timed out by passing a callback function to the error option like so:

error: function(x, t, m){
    //process error here
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top