文档 / 工具库 API / function.uts

function 节流防抖

节流与防抖,返回同一个 CuTimer 形状。

01 / Signature

函数签名

函数签名说明
throttlethrottle(fn: () => void, wait: number = 500): CuTimer首次 run() 立即执行,之后 wait 毫秒内的 run() 丢弃;cancel() 清零窗口
debouncedebounce(fn: () => void, wait: number = 300): CuTimer每次 run() 重置计时,末次调用后 wait 毫秒执行一次;cancel() 取消未到点的执行
CuTimer
export type CuTimer = {
	run: () => void
	cancel: () => void
}
02 / Example

示例

usage
const t = throttle((): void => {
	console.log('tick')
}, 500)
t.run()  // 立即执行
t.run()  // 500ms 内,丢弃
t.cancel()
t.run()  // 立即执行

const d = debounce((): void => {
	console.log('search')
}, 300)
d.run()
d.run()  // 前一次被取消,300ms 后只执行一次
d.cancel()
03 / Notes

注意事项

回调签名固定无参,需要事件对象时在闭包里捕获;没有 flush(),需要立即执行时先 cancel() 再直接调业务函数。窗口用 Date.now() 判定,错过不补偿。