Created
November 19, 2023 08:02
-
-
Save fecoderchinh/7e03e7f6de94eeda48bbe6a26c73bc90 to your computer and use it in GitHub Desktop.
Javascript Debounce & 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
// 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)} |
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
// 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