// 节流
export const throttle = (fn, delay = 1000) => {
//距离上一次的执行时间
let lastTime = 0
return function () {
let _this = this
let _arguments = arguments
let now = new Date().getTime()
//如果距离上一次执行超过了delay才能再次执行
if (now - lastTime > delay) {
fn.apply(_this, _arguments)
lastTime = now
}
}
}
//防抖
export function antiShake(fn, delay, immediate = false) {
let timer = null
//不能用箭头函数
return function () {
//在时间内重复调用的时候需要清空之前的定时任务
if (timer) {
clearTimeout(timer)
}
//适用于首次需要立刻执行的
if (immediate && !timer) {
fn.apply(this,arguments)
}
timer = setTimeout(() => {
fn.apply(this,arguments)
}, delay)
}
}
使用方式
要传参就这样