Skip to content

debounce

Delay a function until after a specified time has elapsed since the last call

248 bytes

Usage

The debounce function helps manage frequent function calls efficiently. It requires two inputs: a delay time (in milliseconds) and a callback. When you use the function returned by debounce (a.k.a. the “debounced function”), it doesn’t immediately run your callback. Instead, it waits for the specified delay.

If called again during this waiting period, it resets the timer. Your source function only runs after the full delay passes without interruption. This is useful for handling rapid events like keystrokes, ensuring your code responds only after a pause in activity.

import * as _ from 'radashi'
// Send a search request to the API server when the user stops typing
// for at least 100ms.
input.addEventListener(
'change',
_.debounce({ delay: 100 }, (event: InputEvent) => {
api.movies.search(event.target.value)
}),
)

Options

leading

When the leading option is true, your callback is invoked immediately the very first time the debounced function is called. After that, the debounced function works as if leading was false.

const myDebouncedFunc = _.debounce({ delay: 100, leading: true }, x => {
console.log(x)
})
myDebouncedFunc(0) // Logs "0" immediately
myDebouncedFunc(1) // Never logs
myDebouncedFunc(2) // Logs "2" about 100ms later

Methods

cancel

The cancel method of the debounced function does two things:

  1. It cancels any pending invocations of the debounced function.
  2. It permanently disables the debouncing behavior. All future invocations of the debounced function will immediately invoke your callback.
const myDebouncedFunc = _.debounce({ delay: 100 }, x => {
console.log(x)
})
myDebouncedFunc(0) // Never logs
myDebouncedFunc(1) // Never logs
myDebouncedFunc.cancel()
myDebouncedFunc(2) // Logs "2" immediately

flush

The flush method will immediately invoke your callback, regardless of whether the debounced function is currently pending.

const myDebouncedFunc = _.debounce({ delay: 100 }, x => {
console.log(x)
})
myDebouncedFunc(0) // Logs "0" about 100ms later
myDebouncedFunc.flush(1) // Logs "1" immediately

isPending

The isPending method returns true if there is any pending invocation of the debounced function.

const myDebouncedFunc = _.debounce({ delay: 100 }, x => {
console.log(x)
})
myDebouncedFunc(0) // Logs "0" about 100ms later
myDebouncedFunc.isPending() // => true
setTimeout(() => {
myDebouncedFunc.isPending() // => false
}, 100)