1

I've an ajax call to set of urls to get html content. But some of the urls are taking long time to get the content, i'm okay to skip those which take more than say 1 sec.

    for (url in list) {
    $.ajax({
        'url': url,
        type: 'get',
        timeout: 1000,
        success: function () {
            //doSomething
        },
        complete: function () {
            //what to write?
        }
    });

}

Can you help me in how to abort the ajax call if it timeouts and execute the complete function.

Lemme know if i'm not clear. Thanks

2 Answers 2

2

First, change $.ajax(function() { to $.ajax({, because the argument you are trying to use is an object, not a function.

Since you specify a timeout in your options object, if the page doesn't respond in time, the ajax method will tell your error function so, as long as you specify one.

$.ajax({
  'url': yourUrlHere,
  success: function(){ /*do stuff*/ },
  timeout: 1000,
  error: function(xhr, status, err){ 
    //status === 'timeout' if it took too long.
    //handle that however you want.
    console.log(status,err); 
  }
});

See the documentation for $.ajax here, as it has a pretty good explanation of the function.

Sign up to request clarification or add additional context in comments.

Comments

0

You can abort the Request if that happens and go on to the next one..

var ajaxRequests = null;
for(url in list){
    var newRequest = $.ajax({
    type: 'GET',
    url: url,
    data: '{}',
    dataType: 'json',
    beforeSend: function() {
        var r = ajaxRequest;
        if (r != null && r != undefined) {
            r.abort();
        }
    },
    success: function(result) {
        // what has to be done if the ajax request comes through
    },
    complete: function() {
        ajaxRequests = null;
    }
    ajaxReqs = newRequest;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.