防抖(Debounce):在事件被触发后,延迟一段时间再执行函数。如果在延迟期间事件再次被触发,则重新计时。常用于搜索框输入、窗口大小调整等场景。
1.不安装任何依赖和库,编写一个防抖的函数
在utils里面增加一个工具函数
/** 防抖 */
export function debounce<T extends (...args: any[]) => any>(func: T,wait: number,immediate: boolean = false//可选,如果true那么会在延迟前立即执行一次
): (...args: Parameters<T>) => void {let timeout: ReturnType<typeof setTimeout> | null = null;return function (this: ThisParameterType<T>, ...args: Parameters<T>) {const context = this;const later = () => {timeout = null;if (!immediate) {func.apply(context, args);}};const callNow = immediate && !timeout;if (timeout) {clearTimeout(timeout);}timeout = setTimeout(later, wait);if (callNow) {func.apply(context, args);}};
}
然后在你需要使用的地方使用就行
const debouncedSaveForm = debounce(saveForm, 300); // 延迟 300 毫秒
<Button type='primary' icon={<SendOutlined />} loading={loading} onClick={debouncedSaveForm}>提交</Button>
简单版本(不需要考虑立即执行的情况)
function debounce(func, wait) {let timeout;return function (...args) {const context = this;clearTimeout(timeout);timeout = setTimeout(() => {func.apply(context, args);}, wait);};
}
2.项目中已经有了Lodash ,可以直接使用内置的_.debounce
方法。
1. 安装 npm install lodash
2. 使用示例
import _ from "lodash";
function sayHello(name) {console.log(`Hello, ${name}!`);
}
const debouncedSayHello = _.debounce(sayHello, 1000);
debouncedSayHello("Alice");