一、防抖:在用户频繁触发的时候,我们只识别一次(识别第一次/最后一次)
【我们可以设置频繁的间隔时间】
/*
debounce:实现函数的防抖(目的是频繁触发中只执行一次)
@params
func: 需要执行的函数
wait: 检测防抖的间隔
immediate: 是否是立即执行(如果为true是控制第一次触发的时候就执行函数,默认false是以最后
一次触发为准)
@return
可被调用执行的函数
*/
function debounce(func, wait = 500, immediate = false) {
let timer = null;
return funciton anonymous(...params){
//如果immediate为true并且没有timer(没有timer说明是第一次),则now为true
let now = immediate && !timer;
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
//执行函数:注意保持this和参数的完整度
!immediate ? func.call(this, ...params) : null;
}, wait)
//如果now为true,则立即执行函数
now ? func.call(this, ...params) : null;
};
}
function func(){
console.log('OK');
}
btn.onclick = debounce(func);
节流
/*
throttle: 实现函数的节流(目的是频繁触发中缩减频率)
@params
func: 需要执行的函数
wait: 自己设定的间隔时间(频率)
@return
可被调用执行的函数
*/
function throttle(func, wait) {
let timer = null,
previous = 0; //记录上一次触发的时间点
return function anonymous(...params) {
let now = new Date(), //记录当前触发的时间
remaining = wait - (now-previous);
//两次间隔时间超过频率:把方法执行即可
if(remaining <= 0) {
previous = now;
func.call(this, ...params);
} else if(!timer){ //当前没有定时器
//两次间隔时间没有超过频率,说明还没有达到触发标准,设置定时器等待即可(还差多久等多久)
clearTimeout(timer);
timer = null;
timer = setTimeout(() => {
previous = new Date();
func.call(this, ...params);
}, remaining)
}
}
}
function func(){
console.log('OK');
}
btn.onclick = throttle(func, 500);