1、防抖
// 参数一fn:需要传入的方法 参数二wait:自定的时间
function antiShaking(fn, wait) {
let timer; // 定义计时器
return function (...args) => {
clearTimeout(timer) // 清除定时器
// 没有计时器,添加计时器,传入要执行的方法,时间
timer = setTimeout(()={
fn.apply(this,args)
}, wait);
}
}
2、节流
// 参数一fn:需要传入的方法 参数二wait:自定的时间
function throttling(fn, wait) {
let timer = null // 定义计时器
return arge => {
if (timer !== null) { // timeOut没有定时器
timer = setTimeout(() => {
fn() // 执行方法
timer = null // 赋空值
}, wait);
}
}
}