Skip to content

Instantly share code, notes, and snippets.

@khrome
Created December 19, 2011 07:21
Show Gist options
  • Save khrome/1495861 to your computer and use it in GitHub Desktop.
Save khrome/1495861 to your computer and use it in GitHub Desktop.
Function.whenTrue polling a boolean function with geometric falloff
if(!Function.actionTimeout) Function.actionTimeout = 16384;
if(!Function.whenTrue){
Function.implement({
whenTrue : function(actionFunction, args, delayFunction, timeoutFunction, timeout, counter){
if(!timeout) timeout = Function.actionTimeout;
if(!counter) counter = 0;
if(!timeoutFunction) timeoutFunction = function(event){
throw('Condition not met after '+event.time+'ms');
};
var result = this();
if(!result){
var delayTime = Math.pow(2, counter); // geometric falloff
if(delayTime >= timeout){
timeoutFunction({
count : counter,
time : delayTime
});
return;
}
counter++;
this.whenTrue.delay(delayTime, this, [actionFunction, args, delayFunction, timeoutFunction, timeout, counter]);
if(delayFunction) delayFunction({
count : counter,
time : delayTime
});
}else{
actionFunction.apply(this, args);
}
}
});
}
(function(){
//code here
}).whenTrue(function(arg1){
//code here
}, [val1]);
myFunction.whenTrue(function(arg1){
//code here
}, [val1]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment