防抖:每次触发事件时设置一个延迟调用方法,并且取消之前的延时调用方法,当你点击一个事件操作停止后才运行后面代码。
节流:高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率,规定你在事件触发一段时间内,只允许执行一次。
vue3 ,vite 项目中
对防抖节流进行封装
// 节流
export const throttle=(fn, time)=> {
let timer: any = null
time = time || 1000
return function(...args) {
if (timer) {
return
}
const _this = this
timer = setTimeout(() => {
timer = null
}, time)
fn.apply(_this, args)
}
}
// 防抖
export const debounce=(fn, time)=> {
time = time || 200
// 定时器
let timer: any = null
return function(...args) {
const _this = this;
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function() {
timer = null
fn.apply(_this, args)
}, time)
}
}