主题
debounce
创建一个防抖回调函数
基本用法
Debounce接受一个带有delay
和源函数的选项对象。当返回的函数被调用时,它只会在经过delay
毫秒后调用源函数。未导致源函数调用的调用会重置延迟,推迟下一次调用。
ts
import { debounce } from 'radash'
const makeSearchRequest = (event) => {
api.movies.search(event.target.value)
}
input.addEventListener('change', debounce({ delay: 100 }, makeSearchRequest))
时序
当delay
为100
时防抖行为的可视化表示。由debounce
返回的函数可以每毫秒调用一次,但它只会在经过delay
毫秒后调用给定的回调。
sh
时间: 0ms - - - - 100ms - - - - 200ms - - - - 300ms - - - - 400ms - - - -
防抖函数调用: x x x x - - - - - - - - x x x x x x x x x x - - - - - - - - - - - -
源函数调用: - - - - - - - - - - x - - - - - - - - - - - - - - - - - x - - - - -
取消
由debounce
返回的函数有一个cancel
方法,调用该方法将永久停止源函数的防抖行为。
ts
const debounced = debounce({ delay: 100 }, api.feed.refresh)
// ... 稍后
debounced.cancel()
立即执行
由debounce
返回的函数有一个flush
方法,调用该方法将直接调用源函数。
ts
const debounced = debounce({ delay: 100 }, api.feed.refresh)
// ... 稍后
debounced.flush(event)
是否待处理
由debounce
返回的函数有一个isPending
方法,调用该方法将返回是否有待处理的源函数调用。
ts
const debounced = debounce({ delay: 100 }, api.feed.refresh)
// ... 稍后
debounced.isPending()