防抖与节流
debounce
创建一个防抖函数。在指定延迟时间内,如果再次调用,会重新计时,只有最后一次调用会在延迟结束后执行。
ts
declare function debounce<T extends AnyCallback>(
func: T,
delay: number
): (...args: Parameters<T>) => void| 参数 | 类型 | 说明 |
|---|---|---|
func | T | 要执行的函数 |
delay | number | 延迟时间(毫秒) |
返回值:防抖后的函数,参数与原函数一致。
示例
tsx
import { debounce } from 'vitarx'
function handleInput(value: string) {
console.log('搜索:', value)
}
// 300ms 内重复输入不会触发,只有停止输入 300ms 后才执行
const debouncedSearch = debounce(handleInput, 300)
// 在输入框中使用
;<input onInput={(e) => debouncedSearch(e.target.value)} />throttle
创建一个节流函数。在指定时间间隔内,只会执行一次回调,确保两次调用之间至少间隔指定时间。
ts
declare function throttle<T extends AnyCallback>(
callback: T,
delay: number
): (...args: Parameters<T>) => void| 参数 | 类型 | 说明 |
|---|---|---|
callback | T | 要执行的函数 |
delay | number | 间隔时间(毫秒) |
返回值:节流后的函数,参数与原函数一致。
示例
tsx
import { throttle } from 'vitarx'
function handleScroll() {
console.log('滚动位置:', window.scrollY)
}
// 每 200ms 最多执行一次
const throttledScroll = throttle(handleScroll, 200)
window.addEventListener('scroll', throttledScroll)下一步
- 延迟与超时 — 了解 sleep 和 withDelayTimeout 工具函数