-
-
Save jupegarnica/0f5c54520034b5f8d5f33908ecd70558 to your computer and use it in GitHub Desktop.
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
| const throttle = (func, time = 17, options = { | |
| leading: true, | |
| trailing: false, | |
| context: null | |
| }) => { | |
| let previous = new Date(0).getTime() | |
| let timer; | |
| const _throttle = function (...args) { | |
| let now = new Date().getTime(); | |
| if (!options.leading) { | |
| if (timer) return | |
| timer = setTimeout(() => { | |
| timer = null | |
| func.apply(options.context, args) | |
| }, time) | |
| } else if (now - previous > time) { | |
| func.apply(options.context, args) | |
| previous = now | |
| } else if (options.trailing) { | |
| clearTimeout(timer) | |
| timer = setTimeout(() => { | |
| func.apply(options.context, args) | |
| }, time) | |
| } | |
| }; | |
| _throttle.cancel = () => { | |
| previous = 0; | |
| clearTimeout(timer); | |
| timer = null | |
| }; | |
| return _throttle | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment