Skip to content

Instantly share code, notes, and snippets.

@benfoxall
Created August 5, 2012 16:51
Show Gist options
  • Select an option

  • Save benfoxall/3265898 to your computer and use it in GitHub Desktop.

Select an option

Save benfoxall/3265898 to your computer and use it in GitHub Desktop.
// the queue of things that are waited for
var waitQueue = (new $.Deferred).resolve().promise();
$.wait = function(waitfor){
var dfr = new $.Deferred();
// poll until a function returns true, then resolves the dfr
// TODO: throw on timeout
var poll = function(fn){
if(fn()) dfr.resolve();
else setTimeout(function(){
poll(fn);
},100);
};
// get a function that will
// resolve this deferred based on `waitfor`
var wString = Object.prototype.toString.call(waitfor);
var fn = {
'[object Function]': function(){
poll(waitfor)
},
'[object String]': function(){
poll(function(){ return $(waitfor).size()})
},
'[object Number]': function(){
setTimeout(dfr.resolve, waitfor)
}
}[wString];
waitQueue.then(fn)
waitQueue = dfr.promise();
return dfr.promise();
};
// the queue of things that are waited for
var waitQueue = (new $.Deferred).resolve().promise();
$.wait = function(waitfor, callback){
var dfr = new $.Deferred();
if(callback)
dfr.then(callback);
// poll until a function returns true, then resolves the dfr
// TODO: throw on timeout
var poll = function(fn){
if(fn()) dfr.resolve();
else setTimeout(function(){
poll(fn);
},100);
};
// get a function that will
// resolve this deferred based on `waitfor`
var wString = Object.prototype.toString.call(waitfor);
var fn = {
'[object Function]': function(){
poll(waitfor)
},
'[object String]': function(){
poll(function(){ return $(waitfor).size()})
},
'[object Number]': function(){
setTimeout(dfr.resolve, waitfor)
}
}[wString];
waitQueue.then(fn)
waitQueue = dfr.promise();
return dfr.promise();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment