参考文章:https://mp.weixin.qq.com/s/qyeRecCBBwa-Zf_V-KIRxA
防抖和节流的概念其实最早并不是出现在软件工程中,防抖是出现在电子元件中,节流出现在流体流动中。
1.为什么要在JavaScript中使用防抖与节流:
-
JavaScript是事件驱动的,大量的操作会触发事件,加入到事件队列中处理。
-
而对于某些频繁的事件处理会造成性能的损耗,我们就可以通过防抖和节流来限制事件频繁的发生;
1.1.防抖:
在第一次触发事件时,不立即执行函数,而是给出一个期限值比如200ms,然后:
- 如果在200ms内没有再次触发事件,那么就执行函数
- 如果在200ms内再次触发事件,那么当前的计时取消,重新开始计时
实现效果:如果短时间内大量触发同一事件,只会执行一次函数。
防抖的应用场景很多:
-
输入框中频繁的输入内容,搜索或者提交信息;
-
频繁的点击按钮,触发某个事件;
-
监听浏览器滚动事件,完成某些特定操作;
-
用户缩放浏览器的resize事件;
总之,密集的事件触发,我们只希望触发比较靠后发生的事件,就可以使用防抖函数;
1.2.节流
实现效果:如果短时间内大量触发同一事件,那么在函数执行一次之后,该函数在指定的时间期限内不再工作,直至过了这段时间才重新生效。
节流的应用场景:
-
监听页面的滚动事件;
-
鼠标移动事件;
-
用户频繁点击按钮操作;
-
游戏中的一些设计;
总之,依然是密集的事件触发,但是这次密集事件触发的过程,不会等待最后一次才进行函数调用,而是会按照一定的频率进行调用;
2.实现防抖函数:
2.1.案例准备
监听input的输入,通过打印模拟网络请求
<body>
<input class="search" type="text">
<script>
// 1.获取输入框
var search = document.querySelector(".search");
// 2.监听输入内容,发送ajax请求
// 2.1.定义一个监听函数
var counter = 0;
function searchChange() {
counter++;
console.log("发送"+ counter +"网络请求");
}
// 绑定oninput
search.oninput = searchChange
</script>
</body>
2.2.第三方库来实现防抖操作
-
lodash
-
underscore
具体案例可以看别的博文
2.3.自定义防抖函数
2.3.1防抖函数的核心思路如下:
-
当触发一个函数时,并不会立即执行这个函数,而是会延迟(通过定时器来延迟函数的执行)
-
如果在延迟时间内,有重新触发函数,那么取消上一次的函数执行(取消定时器);
-
如果在延迟时间内,没有重新触发函数,那么这个函数就正常执行(执行传入的函数);
代码:
function debounce(fn, delay) {
var timer = null;
return function() {
if (timer) clearTimeout(timer);
timer = setTimeout(function() {
fn();
}, delay);
}
}
-
定义debounce函数要求传入两个参数
-
需要处理的函数fn;
-
延迟时间;
-
-
通过定时器来延迟传入函数fn的执行
-
如果在此期间有再次触发这个函数,那么clearTimeout取消这个定时器;
-
如果没有触发,那么在定时器的回调函数中执行即可;
-
2.3.2优化参数和this
function debounce(fn, delay) {
var timer = null;
return function() {
if (timer) clearTimeout(timer);
// 获取this和argument
var _this = this;
var _arguments = arguments;
timer = setTimeout(function() {
// 在执行时,通过apply来使用_this和_arguments
fn.apply(_this, _arguments);
}, delay);
}
}
2.3.3. 优化取消功能
有时候,在等待执行的过程中,可能需要取消之前的操作:
-
比如用户进行了搜索,但是还没有来得及发送搜索的情况下,退出了界面;
-
当用户退出时,之前的操作就可以取消掉;
我们这里将delay时间改长,并且在下方增加一个按钮:
-
在延迟时间内,我们点击按钮,就取消之前的函数执行;
<body>
<input class="search" type="text">
<button class="cancel-btn">取消事件</button>
// 此处封装的是debounce函数
<script>
function debounce(fn, delay) {
var timer = null;
var handleFn = function() {
if (timer) clearTimeout(timer);
// 获取this和argument
var _this = this;
var _arguments = arguments;
timer = setTimeout(function() {
// 在执行时,通过apply来使用_this和_arguments
fn.apply(_this, _arguments);
}, delay);
}
// 取消处理
handleFn.cancel = function() {
if (timer) clearTimeout(timer);
}
return handleFn;
}
</script>
// 业务逻辑js代码
<script>
// 1.获取输入框
var search = document.querySelector(".search");
// 2.监听输入内容,发送ajax请求
// 2.1.定义一个监听函数
var counter = 0;
function searchChange(e) {
counter++;
console.log("发送"+ counter +"网络请求");
console.log(this);
console.log(e.target.value);
}
// 对searchChange处理
var _searchChange = debounce(searchChange, 3000);
// 绑定oninput
search.oninput = _searchChange;
// 3.取消事件
var cancelBtn = document.querySelector(".cancel-btn");
cancelBtn.onclick = function(event) {
_searchChange.cancel();
}
</script>
</body>
2.3.4. 优化立即执行
某些场景是用户开始输入时的第一次是立即执行的,后续的输入才需要等待,我们可以如何优化呢?
-
我们可以让用户多传入一个参数:leading
-
那么第一次就立即执行
-
后来的事件需要等待delay时间执行
-
leading为false,或者不传,那么按照上面的防抖进行操作
-
leading为true
-
-
我们可以根据是否传入leading进行不同的处理方式
function debounce(fn, delay, leading) {
var timer = null;
leading = leading || false;
var handleFn = function() {
if (timer) clearTimeout(timer);
// 获取this和argument
var _this = this;
var _arguments = arguments;
if (leading) {
// 通过一个变量来记录是否立即执行
var isInvoke = false;
if (!timer) {
fn.apply(_this, _arguments);
isInvoke = true;
}
// 定时器通过修改timer来修改instant
timer = setTimeout(function() {
timer = null;
if (!isInvoke) {
fn.apply(_this, _arguments);
}
}, delay);
} else {
timer = setTimeout(function() {
// 在执行时,通过apply来使用_this和_arguments
fn.apply(_this, _arguments);
}, delay);
}
}
// 取消处理
handleFn.cancel = function() {
if (timer) clearTimeout(timer);
}
return handleFn;
}
2.3.5. 优化返回值
有时候fn函数执行结束后还有返回值,如果我们希望拿到这个返回值应该怎么办呢?
先明确一个操作:
-
内部执行fn函数大多数情况是异步执行的(在setTimeout中执行)
-
所以通过return是无法拿到返回值的
异步的操作如何获取返回值呢?
-
ES6中通过Promise
-
ES6之前通过回调函数
2.3.5.1.Promise的版本:
function debounce(fn, delay, leading) {
var timer = null;
leading = leading || false;
var handleFn = function () {
return new Promise((resovle, reject) => {
if (timer) clearTimeout(timer);
// 获取this和argument
var _this = this;
var _arguments = arguments;
if (leading) {
// 通过一个变量来记录是否立即执行
var isInvoke = false;
if (!timer) {
resovle(fn.apply(_this, _arguments));
isInvoke = true;
}
// 定时器通过修改timer来修改instant
timer = setTimeout(function () {
timer = null;
if (!isInvoke) {
resovle(fn.apply(_this, _arguments));
}
}, delay);
} else {
timer = setTimeout(function () {
// 在执行时,通过apply来使用_this和_arguments
resovle(fn.apply(_this, _arguments));
}, delay);
}
})
}
// 取消处理
handleFn.cancel = function () {
if (timer) clearTimeout(timer);
}
return handleFn;
}
2.3.5.2.回调函数版本
因为这一次有多个可选参数,所以我们让调用者传入一个option
-
leading:是否开始的回调直接执行一次
-
result:函数类型,通过它来将结果回调出去
function debounce(fn, delay, option) {
var timer = null;
if (!option) option = {};
leading = option.leading || false;
result = option.result || null;
var handleFn = function () {
if (timer) clearTimeout(timer);
// 获取this和argument
var _this = this;
var _arguments = arguments;
if (leading) {
// 通过一个变量来记录是否立即执行
var isInvoke = false;
if (!timer) {
callFn(_this, _arguments);
isInvoke = true;
}
// 定时器通过修改timer来修改instant
timer = setTimeout(function () {
timer = null;
if (!isInvoke) {
callFn(_this, _arguments);
}
}, delay);
} else {
timer = setTimeout(function () {
// 在执行时,通过apply来使用_this和_arguments
callFn(_this, _arguments);
}, delay);
}
}
function callFn(context, argument) {
var res = fn.apply(context, argument);
if (result) {
result(res);
}
}
// 取消处理
handleFn.cancel = function () {
if (timer) clearTimeout(timer);
}
return handleFn;
}
3.节流函数
3.1.使用第三方库来实现
3.2.自定义节流函数
3.2.1.节流基本功能
节流函数的默认实现思路我们采用时间戳的方式来完成:
-
我们使用一个last来记录上一次执行的时间
-
每次准备执行前,获取一下当前的时间now:
now - last > interval
-
那么函数执行,并且将now赋值给last即可
function throttle(fn, interval) {
var last = 0;
return function() {
// this和argument
var _this = this;
var _arguments = arguments;
var now = new Date().getTime();
if (now - last > interval) {
fn.apply(_this, _arguments);
last = now;
}
}
}
3.2.2. 优化最后执行
默认情况下,我们的防抖函数最后一次是不会执行的
-
因为没有达到最终的时间,也就是条件
now - last > interval
满足不了的 -
但是,如果我们希望它最后一次是可以执行的,那么我们可以让其传入对应的参数来控制
我们来看一下代码如何实现:
-
我们增加了else语句:
-
所以我们可以使用timer变量来记录定时器是否已经开启
-
已经开启的情况下,不需要开启另外一个定时器了
-
else语句表示没有立即执行的情况下,就会开启定时器;
-
但是定时器不需要频繁的开启,开启一次即可
-
-
如果固定的频率中执行了回调函数
-
因为刚刚执行过回调函数,所以定时器到时间时不需要执行;
-
所以我们需要取消定时器,并且将timer赋值为null,这样的话可以开启下一次定时器;
-
-
如果定时器最后执行了,那么timer需要赋值为null
-
因为下一次重新开启时,只有定时器为null,才能进行下一次的定时操作;
-
function throttle(fn, interval) {
var last = 0;
var timer = null;
return function() {
// this和argument
var _this = this;
var _arguments = arguments;
var now = new Date().getTime();
if (now - last > interval) {
if (timer) {
clearTimeout(timer);
timer = null;
}
fn.apply(_this, _arguments);
last = now;
} else if (timer === null) { // 只是最后一次
timer = setTimeout(function() {
timer = null;
fn.apply(_this, _arguments);
}, interval);
}
}
}
我们可以传入一个变量让来确定是否需要最后执行一次:
function throttle(fn, interval, option) {
var last = 0;
var timer = null;
if (!option) option = {};
var trailing = option.trailing || false;
return function() {
// this和argument
var _this = this;
var _arguments = arguments;
var now = new Date().getTime();
if (now - last > interval) {
if (timer) {
clearTimeout(timer);
timer = null;
}
fn.apply(_this, _arguments);
last = now;
} else if (timer === null && trailing) { // 只是最后一次
timer = setTimeout(function() {
timer = null;
fn.apply(_this, _arguments);
}, interval);
}
}
}
3.2.3. 优化取消功能
function throttle(fn, interval) {
var last = 0;
var timer = null;
var handleFn = function() {
// this和argument
var _this = this;
var _arguments = arguments;
var now = new Date().getTime();
if (now - last > interval) {
if (timer) {
clearTimeout(timer);
timer = null;
}
fn.apply(_this, _arguments);
last = now;
} else if (timer === null) { // 只是最后一次
timer = setTimeout(function() {
timer = null;
fn.apply(_this, _arguments);
}, interval);
}
}
handleFn.cancel = function() {
clearTimeout(timer);
timer = null;
}
return handleFn;
}
3.2.4. 优化返回值
采用回调函数:
function throttle(fn, interval, option) {
var last = 0;
var timer = null;
if (!option) option = {};
var trailing = option.trailing || false;
var result = option.result || null;
var handleFn = function() {
// this和argument
var _this = this;
var _arguments = arguments;
var now = new Date().getTime();
if (now - last > interval) {
if (timer) {
clearTimeout(timer);
timer = null;
}
callFn(_this, _arguments);
last = now;
} else if (timer === null && trailing) { // 只是最后一次
timer = setTimeout(function() {
timer = null;
callFn(_this, _arguments);
}, interval);
}
}
handleFn.cancel = function() {
clearTimeout(timer);
timer = null;
}
function callFn(context, argument) {
var res = fn.apply(context, argument);
if (result) {
result(res);
}
}
return handleFn;
}