javascript函数防抖Debounce

469 阅读1分钟

学习目标

  1. 了解什么是防抖
  2. 防抖应用的场景
  3. 实现原理

什么是防抖

定义:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。

问题:针对频繁触发scoll resize绑定的事件函数,有可能短时间多次触发时事件,影响性能

思路:多个函数调用合成一次,给定时间后仅调用最后一次

防抖应用的场景

  1. window的resize,scroll事件
  2. 拖拽过程中的 mousemove事件
  3. 文字输入过程中的keyup等事件

防抖实现原理

<!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>

var count = 1;
var container = document.getElementById('container');

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


// container.onmousemove = getUserAction;
// 第一版
// function debounce(func, wait) {
//   var timeout;
//   return function () {
//       clearTimeout(timeout)
//       timeout = setTimeout(func, wait);
//   }
// }
// 利用闭包来记住wait

// func可能有参数
// func内部的this指向
// func可能有返回结果
// function debounce(func, wait) {
//   var timeout, result;
//   return function (...args) {
//       if(timeout) {
//         clearTimeout(timeout);
//       }

//       timeout = setTimeout(() => {
//         result = func.apply(this, args);
//       }, wait);

//       return result;
//   }
// }

// 触发后立即执行一次
function debounce(func, wait, immediate) {
  var timeout, result;
  return function (...args) {
      if(timeout) {
        clearTimeout(timeout);
      }

      if(immediate && !timeout) {
        console.log(111)
        result = func.apply(this, args);
      }

      timeout = setTimeout(() => {
        console.log(222)
        result = func.apply(this, args);
      }, wait);

      return result;
  }
}

container.onmousemove = debounce(getUserAction, 2000, true);

第三方库

lodash

underscore

反思总结

  1. 首先明白防抖是什么,聊天才可以聊到一块
  2. 知道防抖的应用场景,对症下药
  3. 明白其实现原理,最起码面试的时候,可以写出来。
  4. 学习第三方库的实现,弥补不足。