Skip to content

Instantly share code, notes, and snippets.

@ray-peters
Last active April 1, 2016 04:47
Show Gist options
  • Save ray-peters/65d852577f1ee885467f7ad4cfced8b1 to your computer and use it in GitHub Desktop.
Save ray-peters/65d852577f1ee885467f7ad4cfced8b1 to your computer and use it in GitHub Desktop.
/**
* A dynamic throttling function.
* -> See a demo @ https://jsfiddle.net/raypeters/nkk71qjk/
*
* @method throttleUntil
* @_condition {Function} the function that determines if the next call is locked
* @_options {Object} a namespace for instance options
* @_options.onLeading {Function} ran continuously until locked
* @_options.onTrailing {Function} ran once upon unlock
* @_options.onThrottle {Function} ran if locked
* @return {Function} the dynamically throttled function
*
* Let me know if this helped you!
* @author Ray Peters <[email protected]>
*/
;( function(){
return ( window.throttleUntil = throttleUntil );
function throttleUntil( _condition, _options ) {
var _throttled;
_options = _extend( {
onLeading: false,
onTrailing: false,
onThrottle: false
}, _options );
_verifyFunction( _condition );
return _nudge;
function _nudge() {
var stillThrottled, runTrailing, handler;
stillThrottled = _run( _condition, arguments );
if ( _throttled && ! stillThrottled ) {
runTrailing = true;
}
if ( runTrailing ) {
handler = _options.onTrailing;
} else if ( _throttled ) {
handler = _options.onThrottle;
} else {
handler = _options.onLeading;
}
_throttled = stillThrottled;
return _run( handler, Array.prototype.slice.call( arguments ) );
}
function _run( possibleFn, args ) {
return (
possibleFn &&
_verifyFunction( possibleFn ) &&
possibleFn.apply( possibleFn, args )
);
}
}
function _verifyFunction( possibleFn ) {
if ( ! possibleFn ) {
return false;
} else if ( typeof possibleFn !== "function" ) {
console.info( fn );
throw "throttleUntil() :: ^^ that is not a function!! rabble rabble";
return false;
}
return true;
}
function _extend( target, source ) {
var prop;
target = ( target || {} );
for ( prop in source ) {
if ( typeof source[ prop ] === 'object' ) {
target[ prop ] = _extend( target[ prop ], source[ prop ] );
} else {
target[ prop ] = source[ prop ];
}
}
return target;
}
} )();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment