Skip to main content

06.防抖和节流算法

1 防抖算法

1.1 什么是防抖?

在连续不停的输入中,要及时地针对每个输入都做出计算处理,这个计算量很密集,压力大。而人在往往在输入结束时,才代表着该输入才是要被处理的数据,而整个 输入的过程并不是。所以在用户输入的过程中采样输入进行处理往往会造成计算的浪费和压力,所以需要有个防抖算法,当用户停下来时才取样输入再进行处理才对。 所以防抖就是采样用户输入的同时,避免不必要的计算浪费,这就是防抖算法了。
而防抖算法的实现逻辑就是当用户停止输入后的间隔时间满足预定定时时长,则进行处理。

2.1 防抖算法示例代码

TS 示例
type DebounceFunType  = () => void
type DebounceWaitType = number

export const debounce = (func: DebounceFunType, wait: DebounceWaitType): () => void => {
let timer: ReturnType<typeof setTimeout>;

return () => {
timer && clearTimeout(timer)
timer = setTimeout(() => {
func()
}, wait)
}
}

2 节流算法

2.1 什么是节流算法?

同以上的防抖的算法一样,不过数据的采样不再是用户停止一段时间触发,而是一个固定的时长间隔就是采样用户的输入数据。相当于在一条时间线上,只要用户有输入, 那么隔一段固定时间后就直接采样。

2.2 节流示例代码

TS 示例
type throttlingFunType = () => void;
type throttlingWaitType = number;

export const throttling = (fun: throttlingFunType, wait: throttlingWaitType) => {
type TimeOutType = ReturnType<typeof setTimeout> ;
let timer: TimeOutType | boolean
return () => {
if (!timer) {
timer = setTimeout(() => {
fun()
clearTimeout(timer as TimeOutType)
timer = false
}, wait)
}
}
}