Skip to content

Instantly share code, notes, and snippets.

@rdazvd
Created January 17, 2020 20:05
Show Gist options
  • Save rdazvd/98be019c5a07a0cfa1bd1d22016c0b6f to your computer and use it in GitHub Desktop.
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)
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