Skip to content

Instantly share code, notes, and snippets.

@tobbbe
Forked from beaucharman/debounce.js
Created August 21, 2017 14:23
Show Gist options
  • Save tobbbe/b337f10bfe6dc70febeee2bd4e7be86e to your computer and use it in GitHub Desktop.
Save tobbbe/b337f10bfe6dc70febeee2bd4e7be86e to your computer and use it in GitHub Desktop.
An ES6 implementation of the debounce function. "Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in 'execute this function only if 100 milliseconds have passed without it being called.'" - CSS-Tricks (https://css-tricks.com/the-difference-between-throttling-and-debounc…
function debounce(callback, wait, context = this) {
let timeout = null
let callbackArgs = null
const later = () => callback.apply(context, callbackArgs)
return function() {
callbackArgs = arguments
clearTimeout(timeout)
timeout = setTimeout(later, wait)
}
}
/**
* Normal event
* event | | |
* time ----------------
* callback | | |
*
* Call log only when it's been 100ms since the last sroll
* scroll | | |
* time ----------------
* callback | |
* |100| |100|
*/
/* usage
const handleScroll = debounce((e) => {
console.log('Window scrolled.')
}, 100)
window.addEventListener('scroll', handleScroll)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment