防抖:
在一个动作执行后立即充值状态 单位时间内不再触发的话 函数执行 如果单位时间内触发 则重新计时
function debounce(func, wait, immediate){
let timer = null;
return function(...args){
let context = this;
if (immediate){
let callNow;
if (timer){
clearTimeout(timer)
}
callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, wait)
if (callNow) func.apply(context, args);
}else{
if (!timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(context, args);
timer = null;
}, wait)
}
}
}
节流: 在高速的触发过程中 在单位时间内的触发 会被屏蔽执行 直到单位时间过去 降低调用频率
function throttle(func, wait, type){
let timer = null;
let previous = 0;
return function(...args){
let context = this;
if (type == "timeStamp"){
let nowTime = new Date().getTime();
if (nowTime - previous > wait){
func.apply(context, args);
previous = nowTime;
}
}else{
if (!timer){
timer = setTimeout(() => {
func.apply(context, args);
timer = null;
}, wait)
}
}
}
}