debounce
Delay a function until after a specified time has elapsed since the last call
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'
const processData = (data: string) => { console.log(`Processing data: "${data}"...`)}const debouncedProcessData = _.debounce({ delay: 100 }, processData)
debouncedProcessData('data1') // Never logsdebouncedProcessData('data2') // Never logsdebouncedProcessData('data3') // Processing data: "data3"...
setTimeout(() => { debouncedProcessData('data4') // Processing data: "data4"... (200ms later)}, 200)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" immediatelymyDebouncedFunc(1) // Never logsmyDebouncedFunc(2) // Logs "2" about 100ms laterMethods
cancel
The cancel method of the debounced function does two things:
- It cancels any pending invocations of the debounced function.
- 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 logsmyDebouncedFunc(1) // Never logsmyDebouncedFunc.cancel()myDebouncedFunc(2) // Logs "2" immediatelyflush
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 latermyDebouncedFunc.flush(1) // Logs "1" immediatelyisPending
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 latermyDebouncedFunc.isPending() // => truesetTimeout(() => { myDebouncedFunc.isPending() // => false}, 100)