Created
March 21, 2012 20:24
-
-
Save tjeastmond/2152528 to your computer and use it in GitHub Desktop.
Underscore.js Mixin that takes two functions as arguments, and returns a new function that when called will run the first function until it returns true. When the first function returns true, the second function is fired.
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
// When.js | |
// TJ Eastmond <[email protected]>, SpiteShow | |
// Simple Underscore.js Mixin that runs the first function until | |
// it returns true, then runs the second | |
(function() { | |
// Pass in two functions. The first is checked until it returns true, then the second is run | |
var when = function(truthy, func) { | |
// Just making sure we were passed functions... | |
if (!_.isFunction(truthy) || !_.isFunction(func)) { | |
return false; | |
} | |
// Return the new function with our truth check | |
return function() { | |
// Keep checking for a true result | |
var timer = setInterval(function() { | |
if (truthy() === true) { | |
// Finally got a true, so stop the timer and call the function | |
clearInterval(timer); | |
func.call(arguments); | |
} | |
}, 1); | |
}; | |
}; | |
// Mixin to Underscore.js | |
_.mixin({ when : when }); | |
}).call(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment