Created
February 2, 2018 19:20
-
-
Save dswitzer/b441dc34979b2945bb96bffee44bb9f6 to your computer and use it in GitHub Desktop.
fireThenDebounce() - A variation of a debounce handler which fires off code at the start and end of the execution call stack
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
| /* | |
| * fireThenDebounce(delay, immediate, tail) | |
| * | |
| * delay - number of milliseconds in which to debounce the `trail` callback | |
| * immediate - function to run when the debounce handler starts | |
| * tail - the debounced function to run after the inactive delay is reached | |
| * | |
| * This is a special version of a debounce handler, which allows you to trigger | |
| * off code to run at the start and end of a debounced event. A normal debounce | |
| * event only fires when a debounced event ends. | |
| * | |
| * The `immediate` callback is run any time the debounced function is called. | |
| * This allows you to do some setup when the debouncing begins. The `trail` | |
| * callback is triggered just as a normally debounced function call would | |
| * and only runs after the delay threshold has been might. | |
| * | |
| * Take the following example: | |
| * | |
| * var resizer = fireThenDebounce(10, resetDOMHelpers, addDOMHelpers); | |
| * window.addEventListener("resize", resizer); | |
| * | |
| * As soon as the user starts to resize the window, the `resetDOMHelpers` | |
| * callback would be triggered. As long as the event is fired again within | |
| * 10ms, nothing will happen. As soon as the resize hasn't fired within 10ms | |
| * then the `addDOMHelpers` callback will fire. | |
| * | |
| * As soon as the `trail` callback is fired, the debounce becomes idle again | |
| * and the `immeditate` callback will be fired immediately on the next call. | |
| * | |
| */ | |
| function fireThenDebounce(delay, immediate, tail){ | |
| var timeout | |
| // track if the debounce event is ready for the first run | |
| , idle = true; | |
| return function (){ | |
| var obj = this, args = arguments; | |
| function delayed (){ | |
| timeout = null; | |
| idle = true; | |
| tail.apply(obj, args); | |
| }; | |
| // the immediate function is only run when idle | |
| if( idle === true ){ | |
| immediate.apply(obj, args); | |
| } | |
| // track that we're in the processing of running | |
| idle = false; | |
| // set up the debounce event | |
| if( timeout ) clearTimeout(timeout); | |
| timeout = setTimeout(delayed, delay); | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment