来看一下这段代码
<div id="content" style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;font-size:80px;"></div>
<script>
let num = 1;
let content = document.getElementById('content');
function count() {
content.innerHTML = num++;
};
content.onmousemove = count;
</script>
鼠标移动 页面内的数字会迅速增加
防抖
防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。这个时候,鼠标一直在盒子内移动的话,num是不会增长的
比如我们的「百度搜索」,搜索的时候有关键字的提醒,关键字的来源来自于客户端向服务端请求得到的数据,我们通过「keyup事件」去监听触发请求,如果返回值的搜索key已经不是搜索框现在的值,就丢弃掉这次返回,于是我们提出这样一个「优化需求」:「触发事件,但是我一定在事件触发n秒后才执行,如果你在一个事件触发的n秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行」那么我们来动手实现我们的「第一版」的防抖函数吧:
function debounce(fn,wait){
let timeout
return function(){
if(timeout){
clearTimeout(timeout)
}
timeout=setTimeout(fn,wait)
}
}
demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
#search {
width: 400px;
margin-left: 300px;
margin-bottom: 50px;
}
#showSearch {
width: 800px;
height: 100px;
background: lightblue;
color: red;
margin-left: 300px;
}
</style>
</head>
<body>
<input type="search" name="" id="search" />
<div id="showSearch"></div>
</body>
<script>
function debounce(fn, wait) {
let timeout;
return function() {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(fn, wait);
};
}
let search = document.querySelector("#search");
let showSearch = document.querySelector("#showSearch");
function getSearchInfo(e) {
// showSearch.innerText = this.value; // 报错
// console.log(e); // undefined
showSearch.innerText = search.value;
}
search.onkeyup = debounce(getSearchInfo, 1000);
</script>
</html>
「debounce函数」
返回了一个匿名函数,而这匿名函数又引用了timeout这个变量,这样就形成了闭包,也就是函数的「执行上下文」
的「活动对象」
并不会被销毁,保存了timeout变量,才能实现我们这个「如果你在一个事件触发的n秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行」的需求
修复this指向和event问题
上述中的代码还存留了二个问题就是this问题,我们this指向的不是window对象,而是指向我们的dom对象,第二个就是event对象,event对象在这里会报undefined,那么接下来我们来完善我们的第二版代码吧:
❞
「第二版本的防抖函数」
function debounce(fn, wait) {
let timeout;
return function() {
let context = this;
let args = arguments;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
fn.apply(context, args);
}, wait);
};
}
第二版代码已经实现了,我们来写个demo验证下吧:
let search = document.querySelector("#search");
let showSearch = document.querySelector("#showSearch");
function getSearchInfo(e) {
showSearch.innerText = this.value;
console.log(e);
}
search.onkeyup = debounce(getSearchInfo, 1000);
这里涉及的知识点就是「this指向」
和「arguments、apply」
等,先来说说arguments属性,我们知道可以通过arguments属性获取函数的参数值,而dom事件操作中,会给「回调函数(这里回调函数是debounce函数返回的闭包函数)「传递一个event
参数,这样我们就可以通过arguments
属性拿到event
属性,那么问题二就解决啦,
再来说说问题一的this指向,此时这里keyup事件的回调函数是」debounce函数返回的闭包函数」而不是getSearchInfo函数(「但是我们希望处理业务逻辑的getSearchInfo的this指向能够指向dom对象」),我们知道「this的指向是我最后被谁调用,我就指向谁」
,那么我这里被search调用所以「this指向search」,但是由于有setTimeout异步操作,我们getSearchInfo函数的this指向是window(非严格模式下),所以我们需要改变getSearchInfo的指向,这样我们用apply就完美实现了
立即执行
这时候我们开发的问题解决了,但是万恶的产品又提出了一个新的需求方案:「我不希望非要等到事件停止触发后才执行,我希望立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行」,那我们就来实现这个新需求吧
// 参数immediate值 true||false
function debounce(fn, wait, immediate) {
let timeout;
return function() {
let context = this;
let args = arguments;
if (timeout) {
clearTimeout(timeout);
}
let callNow = !timeout;
if (immediate) {
// 已经执行过,不再执行
timeout = setTimeout(function() {
timeout = null;
}, wait);
if (callNow) fn.apply(context, args);
} else {
timeout = setTimeout(function() {
fn.apply(context, args);
}, wait);
}
};
}
demo使用:
search.onkeyup = debounce(getSearchInfo, 100, true);
取消功能
❝
虽然我们的防抖函数已经很完善了,但是我们希望它能支持「取消的功能」,那接着来完善我们的代码吧
❞
「第三版本的防抖函数」
// 参数immediate值 true||false
function debounce(fn, wait, immediate) {
let timeout;
let debounced = function() {
let context = this;
let args = arguments;
if (timeout) {
clearTimeout(timeout);
}
let callNow = !timeout;
if (immediate) {
// 已经执行过,不再执行
timeout = setTimeout(function() {
timeout = null;
}, wait);
if (callNow) fn.apply(context, args);
} else {
timeout = setTimeout(function() {
fn.apply(context, args);
}, wait);
}
};
debounced.cancel = function() {
clearTimeout(timeout);
timeout = null;
};
return debounced
}
修复result bug
❝
到此,我们的防抖函数基本实现了,但是细心的同学可能会发现,如果fn函数参数存在return值,我们需要去接收它,那么来修复这个小Bug吧
❞
「第四版本的防抖函数」
// 参数immediate值 true||false
function debounce(fn, wait, immediate) {
let timeout, result;
let debounced = function() {
let context = this;
let args = arguments;
if (timeout) {
clearTimeout(timeout);
}
let callNow = !timeout;
if (immediate) {
// 已经执行过,不再执行
timeout = setTimeout(function() {
timeout = null;
}, wait);
if (callNow) {
result = fn.apply(context, args);
}
} else {
timeout = setTimeout(function() {
result = fn.apply(context, args);
console.log(result);
}, wait);
}
};
debounced.cancel = function() {
clearTimeout(timeout);
timeout = null;
};
return debounced;
}
到这里我们的防抖函数已经实现了,大家可以动手实现下
防抖函数的总结
❝
精简成两个需求
❞
非立即执行:,如果你在一个事件触发的n秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行
立即执行:我不希望非要等到事件停止触发后才执行,我希望立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行
我们可以按照「立即执行和非立即执行」
这两个需求去理解我们的防抖函数