Skip to content

debounce 防抖函数

function debounce<T extends (...args: any[]) => any>(callback: T, delay: number): DebouncedFunction<T>

创建一个防抖函数。连续触发时会清除上一次定时器,直到停止触发并等待 delay 毫秒后才执行回调。

参数

参数名说明类型默认值
callback需要防抖的函数T extends (...args: any[]) => any必填
delay防抖延迟时间,单位毫秒number必填

返回值

返回值说明类型
debounced防抖后的函数,包含 cancel() 方法DebouncedFunction<T>

方法

方法说明类型
cancel()清除当前等待中的定时器() => void

示例

基础用法

typescript
import { debounce } from '@mingto/tools'

const search = debounce((keyword: string) => {
  // 请求搜索接口
  console.log(keyword)
}, 300)

search('m')
search('mt')
search('mt-ui')
// 仅最后一次会在 300ms 后执行

取消未执行的回调

typescript
import { debounce } from '@mingto/tools'

const saveDraft = debounce(() => {
  // 自动保存草稿
}, 1000)

saveDraft()
saveDraft.cancel()
// cancel 后,本次未执行的保存会被取消

浏览器事件

typescript
import { debounce } from '@mingto/tools'

const handleResize = debounce(() => {
  console.log(window.innerWidth)
}, 200)

window.addEventListener('resize', handleResize)

// 不再监听时清理
window.removeEventListener('resize', handleResize)
handleResize.cancel()

注意事项

  • 防抖函数在 delay 结束后执行最后一次调用。
  • 调用时保留原函数调用上下文与参数。