It\'s a common pattern to implement timeout of some asynchronous function, using deffered/promise:
// Create a Deferred and return its Promise
function timeout(f
I realize this is 2 years old, but in case someone is looking for the answer...
I think Benjamin was close in that you'll want your timeout to be handled separately, so we'll start with his delay function.
function delay(ms){
var d = $.Deferred();
setTimeout(function(){ d.resolve(); }, ms);
return d.promise();
}
Then, if you wanted to wait before code is executed you can call the method you want delayed as a result of this promise.
function timeout(funct, args, time) {
return delay(time).then(function(){
// Execute asynchronous code and return its promise
// instead of the delay promise. Using "when" should
// ensure it will work for synchronous functions as well.
return $.when(funct.apply(null, args));
});
}
This is usually what I'm trying to do when I go looking for a refresher (why I'm here). However, the question was not about delaying the execution, but throwing an error if it took too long. In that case, this complicates things because you don't want to wait around for the timeout if you don't have to, so you can't just wrap the two promises in a "when". Looks like we need another deferred in the mix. (See Wait for the first of multiple jQuery Deferreds to be resolved?)
function timeout(funct, args, time) {
var d = $.Deferred();
// Call the potentially async funct and hold onto its promise.
var functPromise = $.when(funct.apply(null, args));
// pass the result of the funct to the master defer
functPromise.always(function(){
d.resolve(functPromise)
});
// reject the master defer if the timeout completes before
// the functPromise resolves it one way or another
delay(time).then(function(){
d.reject('timeout');
});
// To make sure the functPromise gets used if it finishes
// first, use "then" to return the original functPromise.
return d.then(function(result){
return result;
});
}
We can streamline this, knowing that in this case the master defer only rejects if the timeout happens first and only resolves if the functPromise resolves first. Because of this, we don't need to pass the functPromise to the master defer resolve, because it's the only thing that could be passed and we're still in scope.
function timeout(funct, args, time) {
var d = $.Deferred();
// Call the potentially async funct and hold onto its promise.
var functPromise = $.when(funct.apply(null, args))
.always(d.resolve);
// reject the master defer if the timeout completes before
// the functPromise resolves it one way or another
delay(time).then(function(){
d.reject('timeout');
});
// To make sure the functPromise gets used if it finishes
// first, use "then" to return the original functPromise.
return d.then(function(){
return functPromise;
});
}