Skip to content

Instantly share code, notes, and snippets.

@MEDHAT-ALHADDAD
Created July 19, 2022 04:30
Show Gist options
  • Save MEDHAT-ALHADDAD/e29282712aa4212b60d057573093809d to your computer and use it in GitHub Desktop.
Save MEDHAT-ALHADDAD/e29282712aa4212b60d057573093809d to your computer and use it in GitHub Desktop.
My Implementation of the Debounce Function
function debounce(callback, interval) {
let invokedFlag = false;
let timer;
const setInvokedFlag = () =>
setTimeout(() => (invokedFlag = false), interval);
return () => {
if (invokedFlag) {
clearTimeout(timer);
timer = setInvokedFlag();
return;
}
invokedFlag = true;
timer = setInvokedFlag();
return callback();
};
}
// UNCOMMENT THESE TO TEST YOUR WORK!
function giveHi() {
return "hi";
}
const giveHiSometimes = debounce(giveHi, 3000);
console.log(giveHiSometimes()); // -> 'hi'
setTimeout(function () {
console.log(giveHiSometimes());
}, 2000); // -> undefined
setTimeout(function () {
console.log(giveHiSometimes());
}, 4000); // -> undefined
setTimeout(function () {
console.log(giveHiSometimes());
}, 8000); // -> 'hi'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment