Skip to content

Instantly share code, notes, and snippets.

@colingourlay
Created November 4, 2013 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colingourlay/7297075 to your computer and use it in GitHub Desktop.
Save colingourlay/7297075 to your computer and use it in GitHub Desktop.
onlyWhen - run a function with its original arguments once a condition is met.
/**
* Creates a wrapped version of a funtion that will run with the original
* arguments, once a condition is met. If the condition is not met, it will
* be checked on a set interval until it is met.
*
* @param {Boolean} condition function you expect to eventually return a truthy value
* @param {Function} func original function to resolve
* @param {Number} interval time to wait between checks
* @return {Function} wrapped function you call can call as it it was the original function
*/
function onlyWhen(condition, func, interval) {
var _this;
var _arguments;
function attemptToResolve() {
if (!condition()) {
setTimeout(attemptToResolve, interval || 100);
} else {
func.apply(_this, _arguments);
}
}
return function () {
_this = this;
_arguments = arguments;
attemptToResolve();
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment