节流
特点:每隔一段时间,只执行一次函数。
应用场景:js中的一些事件如浏览器的resize、scroll,鼠标的mousemove。
作用:高频触发极大地浪费资源,节流可以提高应用的性能。
export function throttle<T extends (...args: any[]) => any>(func: T, wait = 300) {
let lastTime = 0;
return function (this: any, ...args: Parameters<T>) {
const now = Date.now();
if (now - lastTime >= wait) {
lastTime = now;
func.apply(this, args);
}
}
}
举例:
import { throttle } from "@/.."
/** val的值就是我们mousemoveEvent 函数上携带的入参*/
const mousemoveEvent = throttle( (val) => { console.log('这里是需要根据val执行的操作')},300)
防抖
特点:一段时间内只执行最后一次操作。
应用场景:搜索联想功能,高频点击提交(防止表单重复调用接口)。
作用:提高应用性能,对后端交互友好。
export function debound(func: Function, wait: number = 300): (...args: any[]) => void {
let timeout: NodeJS.Timeout; // 指定 timeout 的类型
return function (this: any, ...args: any[]) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, wait);
}
}
举例:
import { debound } from "@/.."
/** val的值就是我们inputSearchEvent 函数上携带的入参*/
const inputSearchEvent = debound( (val) => { console.log('这里是需要根据val执行的操作')},300)