JavaScript 专题系列第一篇,讲解防抖,带你从零实现一个 underscore 的 debounce 函数css
在前端开发中会遇到一些频繁的事件触发,好比:html
为此,咱们举个示例代码来了解事件如何频繁的触发:前端
咱们写个 index.html
文件:git
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1">
<title>debounce</title>
<style> #container{ width: 100%; height: 200px; line-height: 200px; text-align: center; color: #fff; background-color: #444; font-size: 30px; } </style>
</head>
<body>
<div id="container"></div>
<script src="debounce.js"></script>
</body>
</html>复制代码
debounce.js
文件的代码以下:github
var count = 1;
var container = document.getElementById('container');
function getUserAction() {
container.innerHTML = count++;
};
container.onmousemove = getUserAction;复制代码
咱们来看看效果:ajax
从左边滑到右边就触发了 165 次 getUserAction 函数!chrome
由于这个例子很简单,因此浏览器彻底反应的过来,但是若是是复杂的回调函数或是 ajax 请求呢?假设 1 秒触发了 60 次,每一个回调就必须在 1000 / 60 = 16.67ms 内完成,不然就会有卡顿出现。浏览器
为了解决这个问题,通常有两种解决方案:app
今天重点讲讲防抖的实现。函数
防抖的原理就是:你尽管触发事件,可是我必定在事件触发 n 秒后才执行,若是你在一个事件触发的 n 秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行,总之,就是要等你触发完事件 n 秒内再也不触发事件,我才执行,真是任性呐!
根据这段表述,咱们能够写初版的代码:
// 初版
function debounce(func, wait) {
var timeout;
return function () {
clearTimeout(timeout)
timeout = setTimeout(func, wait);
}
}复制代码
若是咱们要使用它,以最一开始的例子为例:
container.onmousemove = debounce(getUserAction, 1000);复制代码
如今随你怎么移动,反正你移动完 1000ms 内再也不触发,我再执行事件。
顿时就从 165 次下降成了 1 次!
棒棒哒,咱们接着完善它。
若是咱们在 getUserAction
函数中 console.log(this)
,在不使用 debounce
函数的时候,this
的值为:
<div id="container"></div>复制代码
可是若是使用咱们的 debounce 函数,this 就会指向 Window 对象!
因此咱们须要将 this 指向正确的对象。
咱们修改下代码:
// 第二版
function debounce(func, wait) {
var timeout;
return function () {
var context = this;
clearTimeout(timeout)
timeout = setTimeout(function(){
func.apply(context)
}, wait);
}
}复制代码
如今 this 已经能够正确指向了。让咱们看下个问题:
JavaScript 在事件处理函数中会提供事件对象 event,咱们修改下 getUserAction 函数:
function getUserAction(e) {
console.log(e);
container.innerHTML = count++;
};复制代码
若是咱们不使用 debouce 函数,这里会打印 MouseEvent 对象,如图所示:
可是在咱们实现的 debounce 函数中,却只会打印 undefined!
因此咱们再修改一下代码:
// 第三版
function debounce(func, wait) {
var timeout;
return function () {
var context = this;
var args = arguments;
clearTimeout(timeout)
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
}复制代码
再注意一个小点,getUserAction 函数多是有返回值的,因此咱们也要返回函数的执行结果
// 第四版
function debounce(func, wait) {
var timeout, result;
return function () {
var context = this;
var args = arguments;
clearTimeout(timeout)
timeout = setTimeout(function(){
result = func.apply(context, args)
}, wait);
return result;
}
}复制代码
到此为止,咱们修复了三个小问题:
这个时候,代码已经非常完善,可是为了让这个函数更加完善,咱们接下来思考一个新的需求。
这个需求就是:
我不但愿非要等到事件中止触发后才执行,我但愿马上执行函数,而后等到中止触发n秒后,才能够从新触发执行。
想一想这个需求也是颇有道理的嘛,那咱们加个 immediate 参数判断是不是马上执行。
// 第五版
function debounce(func, wait, immediate) {
var timeout, result;
return function () {
var context = this;
var args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
// 若是已经执行过,再也不执行
var callNow = !timeout;
timeout = setTimeout(function(){
timeout = null;
}, wait)
if (callNow) result = func.apply(context, args)
}
else {
timeout = setTimeout(function(){
result = func.apply(context, args)
}, wait);
}
return result;
}
}复制代码
最后咱们再思考一个小需求,我但愿能取消 debounce 函数,好比说我 debounce 的时间间隔是 10 秒钟,immediate 为 true,这样的话,我只有等 10 秒后才能从新触发事件,如今我但愿有一个按钮,点击后,取消防抖,这样我再去触发,就能够又马上执行啦,是否是很开心?
为了这个需求,咱们写最后一版的代码:
// 第六版
function debounce(func, wait, immediate) {
var timeout, result;
var debounced = function () {
var context = this;
var args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
// 若是已经执行过,再也不执行
var callNow = !timeout;
timeout = setTimeout(function(){
timeout = null;
}, wait)
if (callNow) result = func.apply(context, args)
}
else {
timeout = setTimeout(function(){
result = func.apply(context, args)
}, wait);
}
return result;
};
debounced.cancel = function() {
clearTimeout(timeout);
timeout = null;
};
return debounced;
}复制代码
演示效果以下:
至此咱们已经完整实现了一个 underscore 中的 debounce 函数,恭喜,撒花!
JavaScript专题系列目录地址:github.com/mqyqingfeng…。
JavaScript专题系列预计写二十篇左右,主要研究平常开发中一些功能点的实现,好比防抖、节流、去重、类型判断、拷贝、最值、扁平、柯里、递归、乱序、排序等,特色是研(chao)究(xi) underscore 和 jQuery 的实现方式。
若是有错误或者不严谨的地方,请务必给予指正,十分感谢。若是喜欢或者有所启发,欢迎star,对做者也是一种鼓励。