防抖与节流
1.防抖(debounce):
1.1 定义
在连续的多次触发同一事件的情况下,给定一个固定的时间间隔(假设 300 ms),该时间间隔内若存在新的触发,则清除之前的定时器并重新计时( 重新计时 300 ms )
表现为在短时间多次触发同一事件,只会执行一次函数(最后触发的那次)。
1.2 实现
function debounce (fn, wait) {
if (typeof fn !== 'function') throw new Error('first param need a function');
if (typeof wait !== 'number') throw new Error('second param need a number');
let timer = null;
// 通过闭包隐藏 debounce 函数内部变量,避免外部意外修改
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, wait)
}
}
问题:
1.在上面代码中,setTimeout 中使用了箭头函数,那么如果不使用箭头函数(而使用 function 普通函数)又该怎么做呢,两者之间有什么区别,这一点会在本文阐述,可以自行先思考一下。
2.如果不使用 arguments ,还有哪种书写方式。
3.为什么要使用 apply ,而不是直接执行
2.节流
2.1 定义
在固定时间间隔(一个时间周期)内,大量触发同一事件,触发事件只会执行一次。周期结束,再次触发事件则开始新的周期
2.2 实现
1.定时器版本
function throttle(fn, delay) {
if (typeof fn !== 'function') throw new Error('first param need a function');
if (typeof wait !== 'number') throw new Error('second param need a number');
let timer = null;
return function() {
if (timer) {
return;
}
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null
}, delay)
}
}
2.时间戳版本
function throttle(fn, delay) {
if (typeof fn !== 'function') throw new Error('first param need a function');
if (typeof delay !== 'number') throw new Error('second param need a number');
let startTime = 0;
return function () {
let currentTime = new Date().getTime();
if (currentTime - startTime > delay) {
fn.apply(this, arguments);
startTime = currentTime;
}
}
}
节流中存在和防抖同样的问题,下面会通过防抖来做例子。
3.防抖节流中引出的问题
以防抖函数举例,先看 2.1 中给出的防抖函数(去掉部分代码)
function debounce (fn, wait) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, wait)
}
}
如何使用
// html
<input id="inputBox" />
// js
const inputBox = document.getElementById('inputBox');
inputBox.addEventListener('keyup', debounce((e) => {
console.log('this:', this)
console.log('e:', e)
console.log('value:', inputBox.value);
}, 1000))
3.1 问题一:为什么要使用箭头函数
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, wait)
在输入框输入1,看下控制台效果:
可以看到,e 是可以拿到的,this 指向 window
然后我们把箭头函数改成 function 的普通函数:
timer = setTimeout(function() {
fn.apply(this, arguments);
timer = null;
}, wait)
可以看到,e 是 undefined,this 指向 window
要知道原因,则需要明白以下几点:
function debounce (fn, wait) {
let timer = null;
return function () {
console.log('isE:', arguments) // arguments 就是 fn 的参数
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, wait)
}
}
在 debounce 中传进一个函数,传进函数的参数是 e,实际上这个参数传递到 debounce 中返回函数的参数。这么说比较绕,我们可以打出来看看(上面代码第四行打印 isE )
可以看出,在 debounce 中的返回函数的参数,就是debounce第一个参数 fn 的参数 e 。
明白上面一点后,再来看箭头函数和普通函数的区别:
箭头函数的 this ,arguments 都取决于其外层第一个普通函数,当使用箭头函数时,this 和 arguments 都是源于 debounce 返回函数的 this 和 arguments,这样自然可以拿到对应的 e;
而当使用普通函数时,function的 this 和 arguments 都来源于其自身,因此 e 是肯定拿不到了,另外需要注意的是,尽管上面的 this 表现出来的都是指向 window,但本质上是不一样的。所以使用普通函数时,需要提前保存 this 。
关于 this 指向问题,可以查阅 JS 作用域,闭包,this
那么如果不想使用箭头函数,也可以在返回函数中提前保存 this 与 arguments,如下:
function debounce (fn, wait) {
let timer = null;
// 通过闭包隐藏 debounce 函数内部变量,避免外部意外修改
return function () {
console.log('isE:', arguments)
if (timer) {
clearTimeout(timer);
}
let _this = this; // 提前保存 this
let args = arguments; // 提前保存 arguments
timer = setTimeout(function() {
fn.apply(_this, args); // 使用提前保存好的 this 和 arguments
timer = null;
}, wait)
}
}
至此,该问题解答完毕。
3.2 问题二:如果不使用 arguments ,还有哪种书写方式
在 3.1 中我们知道了,debounce 的返回函数的参数就是 fn 的传入参数,那么可以使用扩展运算符 … 来获取参数。
function debounce (fn, wait) {
let timer = null;
return function (...args) { // 使用扩展运算符
if (timer) {
clearTimeout(timer);
}
let _this = this;
timer = setTimeout(function() {
fn.apply(_this, args);
timer = null;
}, wait)
}
}
3.3 问题三:为什么要使用 apply ,而不是直接执行 fn
apply 可以用来修改 this 指向和参数。上面两个问题中我们讲述了 this 和 arguments 的问题,在这可以理解,使用 apply 正是为了获取传入函数的 fn 的 this 和 arguments 。
4.防抖节流的应用场景
防抖与节流本质上都是为了避免短时间大量触发时间
防抖一般应用于:
- 输入框请求接口获取相关结果;
- window触发resize的时;
节流一般应用于:
- 鼠标的点击,移动等获取窗口位置,
- 监听滚动事件
当然,具体使用哪种,还是需要根据业务需求来选择