跟着巨人学JS之 防抖

224 阅读3分钟

前言:

本文章非原创,只是看到好的只是自我学习与分享

原创作者: 冴羽 原文链接: debounce | throttle 另外这里面还有超级多的干货 :happy:

debounce

简介

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

  • windowresizescroll
  • mousedownmousemove
  • keyupkeydown
  • ……

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

我们写个 index.html 文件:

<!DOCTYPE html>
<html lang="zh-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 文件的代码如下:

let count = 1;

function getUserAction() {
  container.innerHTML = count++
}

container.onmousemove = getUserAction;

如果从左边滑到右边就触发了 100多 次 getUserAction 函数!

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

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

  • debounce 防抖
  • throttle 节流

原理

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

实现

第一版

// 第一版增加防抖
function debounce(func,wait){
  let timeout
  return function () {
    clearTimeout(timeout)
    timeout = setTimeout(func,wait)
  }
}

container.onmousemove = debounce(getUserAction,100)

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

container.onmousemove = debounce(getUserAction, 100);

现在随你怎么移动,反正你移动完 1000ms 内不再触发,我才执行事件。顿时就从 100多次降低成了 1 次!

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

第二版-this

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

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

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

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

我们修改下代码:

// 第二版 this指向正确对象

function debounce(func,wait){
  let timeout
  return function () {
    let context = this

    clearTimeout(timeout)
    timeout = setTimeout(function(){
      func.call(context)
    },wait)
  }
}
container.onmousemove = debounce(getUserAction,100)

第三版——event 对象

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

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

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

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

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

// 第三版 event 对象
function debounce(func, wait) {
  let timeout
  return function() {
    let context = this
    let args = arguments
     console.log('args: ' + args)
    clearTimeout(timeout)
    timeout = setTimeout(function() {
      console.log('arguments: ' + arguments)
      func.call(context, args)
    }, wait)
  }
}
container.onmousemove = debounce(getUserAction, 100)

第四版——立刻执行

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

这个需求就是:

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

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

// 第四版——立刻执行

function debounce(func, wait, immediate) {

  let timeou
  return function() {
    let context = this
    let args = arguments

    if (timeout) clearTimeout(timeout)
    if (immediate) {
      // 如果已经执行过,不再执行
      var callNow = !timeout
      timeout = setTimeout(function(){
        timeout = null
      },wait)

    } else {
      timeout = setTimeout(function() {
        console.log('arguments: ' + arguments)
        func.call(context, args)
      }, wait)
    }


  }
}

container.onmousemove = debounce(getUserAction, 100,false)

结语

好了 ,今天我们就到这里了,还有更多推荐记得关注哦,在线代码地址在这里: js.jirengu.com/wulem/2/edi…