Created
June 11, 2020 10:51
-
-
Save lski/65f2daa7d0c45ddc6ed2d910e21330c3 to your computer and use it in GitHub Desktop.
A simple debounce higher order 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
/** | |
* Creates a new function that will run the callback a maximum of once at the end of the timeout period. | |
* Useful for using with event listeners that fire often. The opposite of throttling. | |
* | |
* @param delay The length of time in ms before firing the callbcak | |
* @param callback The callback to fire once the time has passed | |
*/ | |
export function debounce(delay, callback) { | |
let _args; | |
let _running = false; | |
return (...args) => { | |
_args = args; | |
if (_running) { | |
return; | |
} | |
_running = true; | |
setTimeout(() => { | |
// Allow another timeout to be created as this will be fired | |
_running = false; | |
// Now call the callback with the last args stored | |
callback(..._args); | |
}, delay); | |
}; | |
} |
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
/** | |
* Creates a new function that will run the callback a maximum of once at the end of the timeout period. | |
* Useful for using with event listeners that fire often. The opposite of throttling. | |
* | |
* @param delay The length of time in ms before firing the callbcak | |
* @param callback The callback to fire once the time has passed | |
*/ | |
export function debounce(delay, callback) { | |
let _args; | |
let _running = false; | |
return (...args) => { | |
_args = args; | |
if (_running) { | |
return; | |
} | |
_running = true; | |
setTimeout(() => { | |
// Allow another timeout to be created as this will be fired | |
_running = false; | |
// Now call the callback with the last args stored | |
callback(..._args); | |
}, delay); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment