定义
防抖:多次点击,只识别一次。假设我设定500ms内重复点击无数次都只算做一次。
节流:多次点击,只按照规定的的时间间隔来执行。比如,我设定每100ms执行一次,那么在500ms的设定时间内,无论点击多少次,都只识别并且执行5次。
防抖debounce
function debounce(func, wait, immediate) {
// 多个参数及传递默认的处理
if (typeof func !== "function") throw new TypeError("func must be an function!");
if (typeof wait === "undefined") wait = 500;
if (typeof wait === "boolean") {
immediate = wait;
wait = 500;
}
if (typeof immediate !== "boolean") immediate = false;
// 设定定时器返回值标识
let timer = null;
return function proxy(...params) {
let self = this,
now = immediate && !timer;
clearTimeout(timer);
timer = setTimeout(function() {
timer = null;
!immediate ? func.call(self, ...params) : null;
}, wait);
// 第一次触发就立即执行
now ? func.call(self, ...params) : null;
};
}
function handle(ev) {
// 具体在点击的时候要处理的业务
console.log('OK', this, ev);
}
submit.onclick = debounce(handle, true);
节流 throttle
在这里插入代码function throttle(func, wait) {
// 多个参数及传递默认的处理
if (typeof func !== "function") throw new TypeError("func must be an function!");
if (typeof wait === "undefined") wait = 500;
// 设定定时器返回值标识
let timer = null,
previous = 0; //设置第一次的操作时间为0
return function proxy(...params) {
let self = this,
now = new Date(),
remaining = wait - (now - previous)
if (remaining <= 0) { //如果间隔时间大于wait,就立即执行
clearTimeout(timer);
timer = null;
func.call(self, ...params);
} else if (!timer) { //如果两次触发的时间小于wait,就设置定时器,继续等待
timer = setTimeout(function() {
clearTimeout(timer);
timer = null;
previous = new Date();
func.call(self, ...params);
}, remaining)
}
}
}
function handle() {
// 具体在点击的时候要处理的业务
console.log('OK');
}
window.onscroll = throttle(handle)片
tips
1.参数要注意判断
2.开始第一次的执行条件要注意,即要不要立即执行函数
3.注意 this的问题 :代码采用了let self=this
4.先记忆,再运用。
参考
珠峰周啸天老师讲解。