0
$.ajax({  
        url: "http://ajaxhttpheaders.appspot.com", 
        dataType: 'jsonp', 

        success: function(headers) { 
            language = headers['Accept-Language']; 
            alert(language);
        },

        //it doesn't work
        //timeout: 2000,

        error: function() { 
            //wait for 2 sec..

            //and if there are no response, do something.. 
        }
    }); 

I found timeout: 2000 option, but it doesn't work.

Deckard
  • 1,409
  • 6
  • 32
  • 59

4 Answers4

1

It's a bit hacky, but this should do the trick:

var cancelled = false;
var errorTimer;
$.ajax({  
    url: "http://ajaxhttpheaders.appspot.com", 
    dataType: 'jsonp', 

    success: function(headers) { 
        if (! cancelled) {
            cancelled = true; // stop timeout code from running
            language = headers['Accept-Language']; 
            alert(language);
        }
    });

});
var errorCode = function () {
    if (!cancelled) {
        cancelled = true;
        alert('Took too long and now we ignore the response!');
    }
};
setTimeout(errorCode, 2000);
Rophuine
  • 724
  • 3
  • 8
0

How to handle a timeout is answered here.

I'm not sure that there are events that can fire at different intervals up until you get a successful response.

Community
  • 1
  • 1
Alex
  • 2,350
  • 2
  • 20
  • 17
0

Your datatype is jsonp and it is clearly mentioned here

script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

xkeshav
  • 53,360
  • 44
  • 177
  • 245
0

Quoting Docs:

Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using $.ajaxSetup() rather than being overridden for specific requests with the timeout option.

Further:

In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578