Skip to content

Instantly share code, notes, and snippets.

@maranomynet
Last active December 26, 2015 04:09
Show Gist options
  • Save maranomynet/7090772 to your computer and use it in GitHub Desktop.
Save maranomynet/7090772 to your computer and use it in GitHub Desktop.
basic function throttling utility function
// returns a throttled function that never runs more than every `delay` milliseconds
// the returned function also has a nice .finish() method.
$.throttleFn = function (func, skipFirst, delay) {
if ( typeof skipFirst === 'number' )
{
delay = skipFirst;
skipFirst = false;
}
delay = delay || 50;
var throttled = 0,
timeout,
_args,
_this,
throttledFn = function () {
_args = arguments;
_this = this;
if ( !throttled )
{
skipFirst ?
throttled++:
func.apply(_this, _args);
timeout = setTimeout(throttledFn.finish, delay);
}
throttled++;
};
throttledFn.finish = function () {
timeout && clearTimeout( timeout );
throttled>1 && func.apply(_this, _args);
throttled = 0;
};
return throttledFn;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment