Skip to content

throttle 节流函数

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

创建一个节流函数。第一次调用会立即执行;在间隔时间内再次调用时,会保留最后一次调用并延迟执行。

参数

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

返回值

返回值说明类型
throttled节流后的函数,包含 cancel() 方法ThrottledFunction<T>

方法

方法说明类型
cancel()清除等待中的定时器,并重置上次执行时间() => void

示例

基础用法

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

const reportScroll = throttle(() => {
  console.log(window.scrollY)
}, 200)

window.addEventListener('scroll', reportScroll)

取消等待中的调用

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

const submit = throttle(() => {
  // 提交请求
}, 1000)

submit()
submit.cancel()

搜索输入节流

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

const fetchSuggestions = throttle((keyword: string) => {
  console.log(keyword)
}, 500)

fetchSuggestions('m')
fetchSuggestions('mt')

注意事项

  • 第一次调用会立即执行。
  • 间隔内多次调用会重置延迟定时器,仅保留最后一次调用参数。