Skip to content

Instantly share code, notes, and snippets.

@fecoderchinh
Created November 19, 2023 08:02
Show Gist options
  • Save fecoderchinh/7e03e7f6de94eeda48bbe6a26c73bc90 to your computer and use it in GitHub Desktop.
Save fecoderchinh/7e03e7f6de94eeda48bbe6a26c73bc90 to your computer and use it in GitHub Desktop.
Javascript Debounce & Throttle
// Executing the callback after number of milliseconds.
const debound = (callback, delay) => {
let timeout = 0;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
callback(...args);
}, delay);
}
}
// usage
// onClick={() => debounce(handleEventFunction, 1000)}
// Executing the callback based on limit time
const throttle = (callback, delay) = {
let shouldWait = false,
lastArgs = null;
return (..args) => {
if(shouldWait) {
lastArgs = args;
return;
}
callback(...args);
shouldWait = true;
setTimeout(() => {
if(lastArgs === null) {
shouldWait = false;
} else {
shouldWait = false;
callback(...lastArgs);
lastArgs = null;
}
}, delay);
}
}
// usage
// onClick={() => throttle(handleEventFunction, 1000)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment