Created
July 19, 2022 04:30
-
-
Save MEDHAT-ALHADDAD/e29282712aa4212b60d057573093809d to your computer and use it in GitHub Desktop.
My Implementation of the Debounce Function
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
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