Prevents function from being called until delay has passed without being called. This prevents excessive computer operations like API calls or heavy calculations.
Curried function with two parameters: function and delay. As long as the debounced function continues to be called within the delay, the original function will not be called.
- search field (onkeyup event)
- auto-complete (onkeyup event)
- getting scroll position (onscroll event)
- resizing of window (onresize event)
const debounce = (callback, delay = 250) => {
let timeoutId
return (...args) => {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => {
timeoutId = null
callback(...args)
}, delay)
}
}
Debounced function is called 10 times, but original greet function fires once as expected.
const greet = name => console.log(`Hello ${name}!`)
const debouncedGreet = debounce(greet, 3000)
for (let i = 0; i < 10; i++) {
debouncedGreet(`${i}`)
}
// Hello 9!
It's also worth checking out lodash's code for debounce and documentation. It's more verbose, but also more optimal as it includes leading and trailing flags like @anurbol's second example above. Just be sure to never import all of lodash due to it's size and import it like this instead: import _debounce from 'lodash/debounce'
. I like prefixing with an underscore in case I need to analyze, refactor, or remove any lodash references later. Alternatively, you can just npm install lodash.debounce.