Reputation: 4161
I'm going to call a function which makes a Synchronous REST API call. I want to somehow timeout on that function call if it does not return within some time. How do I do that?
callBlahService = function(args){
// make actual rest api call
$.ajax{
// arguments
async: false
}
}
callBlahService({
success:function(data){
console.log("blah successful");
},
error: function(data){
console.log("blah failed");
}
});
Upvotes: 0
Views: 2624
Reputation: 795
Looks like you're using JQuery. There is a timeout
setting on $.ajax
that should be use: http://api.jquery.com/jQuery.ajax/
Your error handler will get called if the timeout is exceeded.
$.ajax({
timeout: 1000,
success: function(response) {},
error: function(x, t, m) {
if(t==="timeout") {
alert("timed out!");
}
}
});
Upvotes: 1
Reputation: 8852
timeout
Type: Number
Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. 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. http://api.jquery.com/jQuery.ajax/
Upvotes: 0