Appearance
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')注意事项
- 第一次调用会立即执行。
- 间隔内多次调用会重置延迟定时器,仅保留最后一次调用参数。