Skip to content

Instantly share code, notes, and snippets.

@mflisikowski
Forked from beaucharman/debounce.js
Created May 12, 2020 05:40
Show Gist options
  • Save mflisikowski/40aa13bab2e90d7c8bf530bbd3f06e7f to your computer and use it in GitHub Desktop.
Save mflisikowski/40aa13bab2e90d7c8bf530bbd3f06e7f 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, immediate = false) {
let timeout = null
return function() {
const callNow = immediate && !timeout
const next = () => callback.apply(this, arguments)
clearTimeout(timeout)
timeout = setTimeout(next, wait)
if (callNow) {
next()
}
}
}
/**
* Normal event
* event | | |
* time ----------------
* callback | | |
*
* Call log only when it's been 100ms since the last sroll
* scroll | | |
* time ----------------
* callback | |
* |100| |100|
*/
const handleScroll = debounce((arg, event) => {
console.log(`${arg} ${event.type}`)
}, 100, true)
window.addEventListener('scroll', (event) => {
handleScroll('Event is:', event)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment