这周接到一个需求-给输入框作模糊匹配。这还不简单,监听input事件,取到输入值去调接口不就好了? 然然后端小哥说不行,这个接口的数据量很是大,这种方式调用接口的频率过高,并且用户输入时调用根本没有必要,只要在用户中止输入的那一刻切调接口就好了。 唉?这个场景听起来怎么这么像防抖呢?javascript
那到底什么是防抖呢? 你们必定见过那种左右两边中间放广告位的网站,在网页滚动时,广告位要保持在屏幕中间,就要不断地去计算位置,若是不作限制,在视觉上广告位就像在“抖”。防止这种状况,就叫防抖了!前端
防抖的原理是什么? 我一直以为网上流传的例子很是形象:当咱们在乘电梯时,若是这时有人过来,咱们会出于礼貌一直按着开门按钮等待,等到这人进电梯了,刚准备关门时,发现又有人过来了!咱们又要重复以前的操做,若是电梯空间无限大的话,咱们就要一直等待了。。。固然人的耐心是有限的!因此咱们规定了一个时间,好比10秒,若是10秒都没人来的话,就关电梯门。java
用专业术语归纳就是:在必定时间间隔内函数被触发屡次,但只执行最后一次。后端
最简易版的代码实现:性能优化
function debounce(fn, delay) {
let timer = null;
return function() {
const context = this;
const args = arguments;
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}
复制代码
fn是要进行防抖的函数,delay是设定的延时,debounce返回一个匿名函数,造成闭包,内部维护了一个私有变量timer。咱们一直会触发的是这个返回的匿名函数,定时器会返回一个Id值赋给timer,若是在delay时间间隔内,匿名函数再次被触发,定时器都会被清除,而后从新开始计时。闭包
固然简易版确定不能知足平常的需求,好比可能须要第一次当即执行的,因此要稍作改动:app
function debounce(fn, delay, immediate) {
let timer = null;
return function() {
const context = this;
const args = arguments;
timer && clearTimeout(timer);
if(immediate) {
const doNow = !timer;
timer = setTimeout(() => {
timer = null;
}, delay);
doNow && fn.apply(context, args);
}
else {
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
}
};
}
复制代码
比起简易版,多了个参数immediate来区分是否须要当即执行。其它与简易版几乎一致的逻辑,除了判断当即执行的地方:异步
const doNow = !timer;
timer = setTimeout(() => {
timer = null;
}, delay);
doNow && fn.apply(context, args);
复制代码
doNow变量的值为!timer,只有!timer为true的状况下,才会执行fn函数。第一次执行时,timer的初始值为null,因此会当即执行fn。接下来非第一次执行的状况下,等待delay时间后才能再次触发执行fn。 注意!与简易版的区别,简易版是必定时间屡次内触发,执行最后一次。而当即执行版是不会执行最后一次的,须要再次触发。前端性能
防抖的函数多是有返回值,咱们也要作兼容:函数
function debounce(fn, delay, immediate) {
let timer = null;
return function() {
const context = this;
const args = arguments;
let result = undefined;
timer && clearTimeout(timer);
if (immediate) {
const doNow = !timer;
timer = setTimeout(() => {
timer = null;
}, delay);
if (doNow) {
result = fn.apply(context, args);
}
}
else {
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
}
return result;
};
}
复制代码
可是这个实现方式有个缺点,由于除了第一次当即执行,其它状况都是在定时器中执行的,也就是异步执行,返回值会是undefined。
考虑到异步,咱们也能够返回Promise:
function debounce(fn, delay, immediate) {
let timer = null;
return function() {
const context = this;
const args = arguments;
return new Promise((resolve, reject) => {
timer && clearTimeout(timer);
if (immediate) {
const doNow = !timer;
timer = setTimeout(() => {
timer = null;
}, delay);
doNow && resolve(fn.apply(context, args));
}
else {
timer = setTimeout(() => {
resolve(fn.apply(context, args));
}, delay);
}
});
};
}
复制代码
如此,只要fn被执行,那一定能够拿到返回值!这也是防抖的终极版了!
下次聊聊防抖的兄弟-前端性能优化之节流-throttle。