Skip to content

Instantly share code, notes, and snippets.

@treyhuffine
Created January 7, 2020 04:57
Show Gist options
  • Save treyhuffine/e7f24828455bbb9d7e232c7d2df9e1d9 to your computer and use it in GitHub Desktop.
Save treyhuffine/e7f24828455bbb9d7e232c7d2df9e1d9 to your computer and use it in GitHub Desktop.
const throttle = (callback, delay) => {
let throttleTimeout = null;
let storedEvent = null;
const throttledEventHandler = event => {
storedEvent = event;
const shouldHandleEvent = !throttleTimeout;
if (shouldHandleEvent) {
callback(storedEvent);
storedEvent = null;
throttleTimeout = setTimeout(() => {
throttleTimeout = null;
if (storedEvent) {
throttledEventHandler(storedEvent);
}
}, delay);
}
};
return throttledEventHandler;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment