在 WEB 开发中的“节流”和“防抖”的不同
在 WEB 开发中的“节流”和“防抖”的不同
- 节流(Throttling): 强制一个函数在一定时间内的最大调用次数。比如说:每 100ms 内最多执行该函数一次;
- 防抖(Debouncing):强制一个函数在一定时间内未被调用的情况下才能执行。比如说:100ms 内没有执行过该函数的情况下再执行。
Throttling 是在固定的时间内执行一次;而 Debounce 是动态的,它要求在一定的时间内没有执行过后才执行,也就说他会重置时间。
假设有个 button 的 click 事件回调函数,不妨称之为 handleClick,此时你在在 3 秒内你每隔 0.5秒点击一次,那么如果设置 Throttling 和 Debounce 均为一秒,那么在 3 秒后你停止点击该 button,此时
- Throttling:执行 handleClick 3次
- Debounce:执行 handleClick 1次
具体应用
export default function App() {
const [path, setPath] = React.useState(
'the-road-to-learn-react/the-road-to-learn-react'
);
React.useEffect(() => {
onFetchFromGitHub(path);