Created
January 17, 2020 20:05
-
-
Save rdazvd/98be019c5a07a0cfa1bd1d22016c0b6f to your computer and use it in GitHub Desktop.
Versatile debouncing function (useful for dynamically calling functions triggered by frequent user events)
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
const debounce = (functionToBeCalled, delay = 1000) => { | |
let timeoutId; | |
return (...functionArgs) => { | |
if (timeoutId) clearTimeout(timeoutId); | |
timeoutId = setTimeout( | |
() => functionToBeCalled.apply(null, functionArgs), | |
delay | |
); | |
}; | |
}; | |
const aFunctionToCall = (eventValue) => console.log(`function called in response to ${eventValue}`); | |
// this example call uses the default value for delay | |
const onInput = debounce(event => aFunctiontoCall(event.target.value)); | |
const input = document.querySelector("input"); | |
input.addEventListener("input", onInput); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment