Created
February 13, 2020 14:55
-
-
Save jll90/fb3f4c331f7181404cb331cd2daa15e5 to your computer and use it in GitHub Desktop.
JavaScript Throttle & Debounce Comparison
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
const throttle = (func, limit) => { | |
let engaged = false; | |
return function () { | |
const args = arguments; | |
const context = this; | |
if (!engaged) { | |
func.apply(context, args); | |
engaged = true; | |
setTimeout(() => engaged = false, limit); | |
} | |
} | |
} | |
const debounce = (func, delay) => { | |
let engaged = null; | |
return function () { | |
const args = arguments; | |
const context = this; | |
clearTimeout(engaged); | |
engaged = setTimeout(() => func.apply(context, args), delay) | |
} | |
} | |
const testThrottle = () => { | |
console.log('throttle'); | |
} | |
const testDebounce = () => { | |
console.log('debounce'); | |
} | |
const throttledFn = throttle(testThrottle, 500); | |
const debouncedFn = debounce(testDebounce, 1000); | |
throttledFn(); | |
throttledFn(1); | |
setTimeout(() => throttledFn(), 600); | |
setTimeout(() => throttledFn(), 700); | |
const debounceInterval = setInterval(() => debouncedFn(), 950); | |
setTimeout(() => { | |
clearInterval(debounceInterval); | |
}, 10000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment