JavaScript专题--傻兮兮的笑着学防抖

前言

在前端开发中会遇到一些频繁的事件触发,比如:

  1. window 的 resize、scroll
  2. mousedown、mousemove
  3. keyup、keydown
    ……

为此,我们举个示例代码来了解事件如何频繁的触发:

我们写个 index.html 文件:

 1 <!DOCTYPE html>
 2 <html lang="zh-cmn-Hans">
 3 
 4 <head>
 5     <meta charset="utf-8">
 6     <meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1">
 7     <title>debounce</title>
 8     <style>
 9         #container{
10             width: 100%; height: 200px; line-height: 200px; text-align: center; color: #fff; background-color: #444; font-size: 30px;
11         }
12     </style>
13 </head>
14 
15 <body>
16     <div id="container"></div>
17     <script src="debounce.js"></script>
18 </body>
19 
20 </html>

debounce.js 文件的代码如下:

1 var count = 1;
2 var container = document.getElementById('container');
3 
4 function getUserAction() {
5     container.innerHTML = count++;
6 };
7 
8 container.onmousemove = getUserAction;

从左边滑到右边就触发了 66 次 getUserAction 函数!

因为这个例子很简单,所以浏览器完全反应的过来,可是如果是复杂的回调函数或是 ajax 请求呢?假设 1 秒触发了 60 次,每个回调就必须在 1000 / 60 = 16.67ms 内完成,否则就会有卡顿出现。

为了解决这个问题,一般有两种解决方案:

  1. debounce 防抖
  2. throttle 节流

防抖

今天重点讲讲防抖的实现。

防抖的原理就是:你尽管触发事件,但是我一定在事件触发 n 秒后才执行,如果你在一个事件触发的 n 秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行,总之,就是要等你触发完事件 n 秒内不再触发事件,我才执行,真是任性呐!

第一版

根据这段表述,我们可以写第一版的代码:

1 // 第一版
2 function debounce(func, wait) {
3     var timeout;
4     return function () {
5         clearTimeout(timeout)
6         timeout = setTimeout(func, wait);
7     }
8 }

如果我们要使用它,以最一开始的例子为例:

1 container.onmousemove = debounce(getUserAction, 1000);

现在随你怎么移动,反正你移动完 1000ms 内不再触发,我才执行事件。

顿时就从 165 次降低成了 1 次!

棒棒哒,我们接着完善它。

this

如果我们在 getUserAction 函数中 console.log(this),在不使用 debounce 函数的时候,this 的值为:

1 <div id="container"></div>

但是如果使用我们的 debounce 函数,this 就会指向 Window 对象!

所以我们需要将 this 指向正确的对象。

我们修改下代码:

 1 // 第二版
 2 function debounce(func, wait) {
 3     var timeout;
 4 
 5     return function () {
 6         var context = this;
 7 
 8         clearTimeout(timeout)
 9         timeout = setTimeout(function(){
10             func.apply(context)
11         }, wait);
12     }
13 }

现在 this 已经可以正确指向了。让我们看下个问题:

event 对象

JavaScript 在事件处理函数中会提供事件对象 event,我们修改下 getUserAction 函数:

1 function getUserAction(e) {
2     console.log(e);
3     container.innerHTML = count++;
4 };

如果我们不使用 debouce 函数,这里会打印 MouseEvent 对象。

但是在我们实现的 debounce 函数中,却只会打印 undefined!

所以我们再修改一下代码:

 1 // 第三版
 2 function debounce(func, wait) {
 3     var timeout;
 4 
 5     return function () {
 6         var context = this;
 7         var args = arguments;
 8 
 9         clearTimeout(timeout)
10         timeout = setTimeout(function(){
11             func.apply(context, args)
12         }, wait);
13     }
14 }

到此为止,我们修复了两个小问题:

  1. this 指向
  2. event 对象

立刻执行

这个时候,代码已经很是完善了,但是为了让这个函数更加完善,我们接下来思考一个新的需求。

这个需求就是:

我不希望非要等到事件停止触发后才执行,我希望立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行。

想想这个需求也是很有道理的嘛,那我们加个 immediate 参数判断是否是立刻执行。

 1 // 第四版
 2 function debounce(func, wait, immediate) {
 3 
 4     var timeout;
 5 
 6     return function () {
 7         var context = this;
 8         var args = arguments;
 9 
10         if (timeout) clearTimeout(timeout);
11         if (immediate) {
12             // 如果已经执行过,不再执行
13             var callNow = !timeout;
14             timeout = setTimeout(function(){
15                 timeout = null;
16             }, wait)
17             if (callNow) func.apply(context, args)
18         }
19         else {
20             timeout = setTimeout(function(){
21                 func.apply(context, args)
22             }, wait);
23         }
24     }
25 }

返回值

此时注意一点,就是 getUserAction 函数可能是有返回值的,所以我们也要返回函数的执行结果,但是当 immediate 为 false 的时候,因为使用了 setTimeout ,我们将 func.apply(context, args) 的返回值赋给变量,最后再 return 的时候,值将会一直是 undefined,所以我们只在 immediate 为 true 的时候返回函数的执行结果。

 1 // 第五版
 2 function debounce(func, wait, immediate) {
 3 
 4     var timeout, result;
 5 
 6     return function () {
 7         var context = this;
 8         var args = arguments;
 9 
10         if (timeout) clearTimeout(timeout);
11         if (immediate) {
12             // 如果已经执行过,不再执行
13             var callNow = !timeout;
14             timeout = setTimeout(function(){
15                 timeout = null;
16             }, wait)
17             if (callNow) result = func.apply(context, args)
18         }
19         else {
20             timeout = setTimeout(function(){
21                 func.apply(context, args)
22             }, wait);
23         }
24         return result;
25     }
26 }

取消

最后我们再思考一个小需求,我希望能取消 debounce 函数,比如说我 debounce 的时间间隔是 10 秒钟,immediate 为 true,这样的话,我只有等 10 秒后才能重新触发事件,现在我希望有一个按钮,点击后,取消防抖,这样我再去触发,就可以又立刻执行啦,是不是很开心?

为了这个需求,我们写最后一版的代码:

 1 // 第六版
 2 function debounce(func, wait, immediate) {
 3 
 4     var timeout, result;
 5 
 6     var debounced = function () {
 7         var context = this;
 8         var args = arguments;
 9 
10         if (timeout) clearTimeout(timeout);
11         if (immediate) {
12             // 如果已经执行过,不再执行
13             var callNow = !timeout;
14             timeout = setTimeout(function(){
15                 timeout = null;
16             }, wait)
17             if (callNow) result = func.apply(context, args)
18         }
19         else {
20             timeout = setTimeout(function(){
21                 func.apply(context, args)
22             }, wait);
23         }
24         return result;
25     };
26 
27     debounced.cancel = function() {
28         clearTimeout(timeout);
29         timeout = null;
30     };
31 
32     return debounced;
33 }

那么该如何使用这个 cancel 函数呢?依然是以上面的 demo 为例:

 1 var count = 1;
 2 var container = document.getElementById('container');
 3 
 4 function getUserAction(e) {
 5     container.innerHTML = count++;
 6 };
 7 
 8 var setUseAction = debounce(getUserAction, 10000, true);
 9 
10 container.onmousemove = setUseAction;
11 
12 document.getElementById("button").addEventListener('click', function(){
13     setUseAction.cancel();
14 })

至此我们已经完整实现了一个 underscore 中的 debounce 函数,恭喜,撒花!鼓掌!哗哗哗~~~

演示代码

相关的代码可以在 Github 博客仓库 中找到

专题系列

JavaScript专题系列目录地址:https://github.com/fanfanSky/BlogDemo

 

如果有错误或者不严谨的地方,请务必给予指正,十分感谢。如果喜欢或者有所启发,欢迎 star。

posted @ 2021-01-05 21:18  ℡北瞳少年、  阅读(120)  评论(0编辑  收藏  举报