1.防抖:在用户频发触发的时候,只识别一次(识别第一次或最后一次)
第一种方法
防抖方法
将上述封装成防抖函数
2.节流:频繁触发中缩减频率 应用如控制滚动条
设置标识,防止频繁点击触发
常用工具库,lodash、underscore有触发和节流的方法
源代码
btn.onclick = throttle(func, 100000)
//----------节流///----------------
function throttle(func, wait = 500) {
console.log(wait)
let timer = null,
previous = 0; //记录上一次操作时间
return function anonymous(...params) {
let now = new Date(), //当前操作的时间
remaining = wait - (now - previous);
if (remaining <= 0) {
// 两次间隔时间超过频率:把方法执行即可
clearTimeout(timer);
timer = null;
previous = now;
func.call(this, ...params);
} else if (!timer) {
// 两次间隔时间没有超过频率,说明还没有达到触发标准呢,设置定时器等待即可(还差多久等多久)
timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
previous = new Date();
func.call(this, ...params);
}, remaining);
}
};
}
///------防抖-------
function debounce(func, wait = 500, immediate = false) {
let timer = null;
return function anonymous(...params) {
let now = immediate && !timer;
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
// 执行函数:注意保持THIS和参数的完整度
!immediate ? func.call(this, ...params) : null;
}, wait);
now ? func.call(this, ...params) : null;
};
}
function func() {
console.log(new Date)
console.log("hello")
}