Created
February 14, 2017 20:24
-
-
Save baldore/cea3d6e8ab5cd0cca753e95c2d0a0b7a to your computer and use it in GitHub Desktop.
Throttle
This file contains hidden or 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 and returns a new, throttled version of the passed function, | |
* that, when invoked repeatedly, will only actually call the original | |
* function at most once per every wait milliseconds. | |
* | |
* @param {function} func | |
* @param {number} threshold | |
* @param {object} [scope] custom this | |
* @returns {function} throttled function | |
*/ | |
export function throttle(func, threshold, scope) { | |
const FUNC_ERROR_TEXT = 'First parameter must be a function.'; | |
let last; | |
let deferTimer; | |
if (typeof func !== 'function') { | |
throw new TypeError(FUNC_ERROR_TEXT); | |
} | |
return function throttled(...args) { | |
const context = this || scope; | |
const now = +new Date(); | |
if (last && now < last + threshold) { | |
clearTimeout(deferTimer); | |
deferTimer = setTimeout(() => { | |
last = now; | |
func.apply(context, args); | |
}, threshold); | |
} else { | |
last = now; | |
func.apply(context, args); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment