Last active
April 9, 2022 06:07
-
-
Save aryankarim/8f5aacf2d177b0eb2ef2edfd2569ab16 to your computer and use it in GitHub Desktop.
Debounce and Throttle
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(cb, wait = 1000) { | |
let timeout; | |
return (...args) => { | |
clearTimeout(timeout); | |
timeout = setTimeout(cb(...args), wait); | |
} | |
} |
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 throttle(cb, delay = 1000) { | |
let shouldWait = false | |
let waitingArgs | |
const timeoutFunc = () => { | |
if (waitingArgs == null) { | |
shouldWait = false | |
} else { | |
cb(...waitingArgs) | |
waitingArgs = null | |
setTimeout(timeoutFunc, delay) | |
} | |
} | |
return (...args) => { | |
if (shouldWait) { | |
waitingArgs = args | |
return | |
} | |
cb(...args) | |
shouldWait = true | |
setTimeout(timeoutFunc, delay) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment