Skip to content

debounce

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

282 bytes
since v12.1.0

Usage

Create a new function that delays invoking a callback until after a specified time has elapsed since the last call.

import * as _ from 'radashi'
// Debounce a search function to avoid making API calls on every keystroke
const searchAPI = _.debounce({ delay: 300 }, async query => {
try {
const response = await fetch(`https://api.example.com/search?q=${query}`)
const results = await response.json()
displayResults(results)
} catch (error) {
console.error('Search failed:', error)
}
})
// Simulate user typing in a search box
document.querySelector('#search-input').addEventListener('input', event => {
const query = event.target.value
searchAPI(query)
})
function displayResults(results) {
// Update UI with search results
console.log('Search results:', results)
}
const debouncedProcessData = _.debounce({ delay: 100 }, processData)

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 debouncedFunc = _.debounce({ delay: 100, leading: true }, x => {
console.log(x)
})
debouncedFunc(0) // Logs "0" immediately
debouncedFunc(1) // Never logs
debouncedFunc(2) // Logs "2" about 100ms later

Return type

The DebounceFunction type is used to represent a debounced function in TypeScript. It has the following properties:

  • callee: The underlying function that is debounced.
  • flush: A method that forces a debounced call to execute immediately.
  • cancel: A method that cancels a debounced function.

Flushing

The flush method forces a debounced call to execute immediately. If no call was currently scheduled, this method does nothing. So you’re effectively saying “execute the function now, but only if it’s scheduled to execute.”

const debouncedFunc = _.debounce({ delay: 1000 }, () => {
console.log('Flushed')
})
debouncedFunc.flush()

The flush method is set to noop when no pending call is scheduled.

Cancelling

The cancel method can be used to cancel a debounced function. Future calls still get debounced, but the currently pending call is immediately cancelled.

const debouncedFunc = _.debounce({ delay: 1000 }, () => {
console.log('Flushed')
})
debouncedFunc()
debouncedFunc.cancel()