什么是截流和防抖?
防抖:在高频事件触发后N秒内,该功能仅执行一次。如果在N秒内再次触发高频事件,将重新计算时间。
截流:触发高频事件,但它仅在N秒内执行一次,因此节流将稀释函数的执行频率。
防抖和节流的区别
防抖是将多个执行更改为最后一个执行。截流是将多个执行更改为间隔执行。
React中开发截流和防抖
import { useCallback, useRef, useEffect } from 'react'
// 基础版防抖
export function debounce(fn, ms) {
let timer;
return function(...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn(...args)
timer = null;
}, ms);
}
}
// 进阶版防抖
export function useDebounce(fn, delay, dep = []) {
const { current } = useRef({ fn, timer: null });
useEffect(function () {
current.fn = fn;
}, [fn]);
return useCallback(function f(...args) {
if (current.timer) {
clearTimeout(current.timer);
}
current.timer = setTimeout(() => {
current.fn.call(this, ...args);
}, delay);
}, dep)
}
// 截流
export function useThrottle(fn, delay, dep = []) {
const { current } = useRef({ fn, timer: null });
useEffect(function () {
current.fn = fn;
}, [fn]);
return useCallback(function f(...args) {
if (!current.timer) {
current.timer = setTimeout(() => {
delete current.timer;
}, delay);
current.fn.call(this, ...args);
}
}, dep);
}
参考链接:https://blog.youkuaiyun.com/qq1361200/article/details/112253863