Created
November 4, 2013 02:03
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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