Last active
December 26, 2015 04:09
-
-
Save maranomynet/7090772 to your computer and use it in GitHub Desktop.
basic function throttling utility function
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
// 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