Curry
Create a debounced callback function
Debounce accepts an options object with delay
, leading
, and a source function to call
when invoked. When the returned function is invoked it will only call the source
function after the delay
milliseconds of time has passed. Calls that don’t result
in invoking the source reset the delay, pushing off the next invocation. The leading
option decides whether the source function is called on the first invocation of the debounce
function or not.
import { debounce } from 'radash'
const makeSearchRequest = event => {
api.movies.search(event.target.value)
}
input.addEventListener('change', debounce({ delay: 100 }, makeSearchRequest))
A visual of the debounce behavior when delay
is 100
. The debounce function
returned by debounce
can be called every millisecond but it will only call
the given callback after delay
milliseconds have passed.
Time: 0ms - - - - 100ms - - - - 200ms - - - - 300ms - - - - 400ms - - - -
debounce Invocations: x x x x - - - - - - - - x x x x x x x x x x - - - - - - - - - - - -
Source Invocations: - - - - - - - - - - x - - - - - - - - - - - - - - - - - x - - - - -
The leading
option, false
by default, will call the source function immediately
the first time the debounce function is invoked when set to true
.
// hide the header when scroll down and show it when scroll up.
const header = document.getElementById('page-header')
let lastY = 0
window.addEventListener(
'scroll',
debounce({ delay: 100, leading: true }, () => {
header.style.transform = `translateY(${
window.scrollY - lastY > 0 ? '-100%' : '0'
})`
lastY = window.scrollY
})
)
The function returned by debounce
has a cancel
method that when called will permanently stop the source function from being debounced.
const debounced = debounce({ delay: 100 }, api.feed.refresh)
// ... sometime later
debounced.cancel()
The function returned by debounce
has a flush
method that when called will directly invoke the source function.
const debounced = debounce({ delay: 100 }, api.feed.refresh)
// ... sometime later
debounced.flush(event)
The function returned by debounce
has a isPending
method that when called will return if there is any pending invocation the source function.
const debounced = debounce({ delay: 100 }, api.feed.refresh)
// ... sometime later
debounced.isPending()