从搜索系统来聊聊防抖和节流

最近公司作一个内部的搜索系统,由于搜索框须要搜索功能须要频繁的去发送请求,这很明显的会给服务器带来压力,那么这时候就要用到防抖和节流的知识点了javascript

防抖函数debounce

好比咱们的百度搜索,搜索的时候有关键字的提醒,关键字的来源来自于客户端向服务端请求获得的数据,咱们经过keyup事件去监听触发请求,若是返回值的搜索key已经不是搜索框如今的值,就丢弃掉此次返回,因而咱们提出这样一个优化需求触发事件,可是我必定在事件触发n秒后才执行,若是你在一个事件触发的n秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行css

那么咱们来动手实现咱们的初版的防抖函数吧:html

function debounce(fn,wait){
     let timeout
     return function(){
         if(timeout){
             clearTimeout(timeout)
         }
        timeout=setTimeout(fn,wait)
     }
}
复制代码

初版代码已经实现了,咱们来写个demo验证下吧:java

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

复制代码

效果图:服务器

能够看到执行上面的demo,咱们输入值之后不触发keyup事件就会隔1秒钟蓝色div才会出现字,若是你一直触发是不会显示的等到你中止触发后的一秒后才显示

有同窗可能对初版代码以为挺简单的,确实简单,不过我仍是要啰嗦几句,初版的代码中,debounce函数返回了一个匿名函数,而这匿名函数又引用了timeout这个变量,这样就造成了闭包,也就是函数的执行上下文活动对象并不会被销毁,保存了timeout变量,才能实现咱们这个若是你在一个事件触发的n秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行的需求闭包

修复this指向和event问题

显然上述中的代码还存留了二个问题就是this问题,咱们this指向的不是window对象,而是指向咱们的dom对象,第二个就是event对象,event对象在这里会报undefined,那么接下来咱们来完善咱们的第二版代码吧:app

第二版本的防抖函数dom

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 秒后,才能够从新触发执行

咱们能够按照当即执行和非当即执行这两个需求去理解咱们的防抖函数

节流 throttle

持续触发事件,每隔一段时间,只执行一次事件。

节流相对来讲仍是很好理解了,固然了他也有跟防抖函数同样有当即执行和非当即执行两个需求,那咱们实现throttle函数的代码吧

当即执行

咱们可使用时间戳,当触发事件的时候,咱们取出当前的时间戳,而后减去以前的时间戳(最一开始值设为 0),若是大于设置的时间周期,就执行函数,而后更新时间戳为当前的时间戳,若是小于,就不执行

function throttle(fn, wait) {
      let context, args;
      let previous = 0;
      return function() {
        let now = +new Date();
        context = this;
        args = arguments;
        if (now - previous > wait) {
          fn.apply(context, args);
          previous = now;
        }
      };
    }
复制代码

demo使用:

demo跟上述防抖用是同样

search.onkeyup = throttle(getSearchInfo, 3000);
复制代码

这里的节流当即执行版跟咱们的防抖初版的知识点原理同样,再也不过多的赘述

非当即执行

非当即执行就是过了n秒后咱们再执行,那么咱们天然而然想到定时器

function throttle(fn, wait) {
      let timeout;
      return function() {
        let context = this;
        let args = arguments;
        // 这里不须要清除定时器 清除了会从新计算时间
        // 清除这个定时器不表明timeout为空
        if (timeout) {
          return false;
        }
        timeout = setTimeout(function() {
          fn.apply(context, args);
          timeout = null;
        }, wait);
      };
    }
复制代码

demo使用

function getSearchInfo(e) {
      console.log(this.value);
      // 验证的效果是 showSearch多久才能读到这个this.value
      showSearch.innerText = this.value;

    }
    search.onkeyup = throttle(getSearchInfo, 3000);
复制代码

此次的效果是等待过了三秒才执行,那咱们来比较当即执行和非当即执行的效果

  • 当即执行会马上执行,非当即执行会在 n 秒后第一次执行
  • 当即执行中止触发后没有办法再执行事件,非当即执行中止触发后依然会再执行一次事件

一统当即执行和非当即执行

咱们的需求想要这样:我触发这个事件想要当即执行,事件中止触发后再执行一遍,也就是n秒内,假设我触发事件大于等于两次先会当即执行,最后会再触发一次

function throttle(fn, wait) {
      let timeout, remaining, context, args;
      let previous = 0;
      // timeout等于null,表明定时器已经完成
      // 最后触发的函数
      let later = function() {
        previous = +new Date();
        timeout = null;
        fn.apply(context, args);
        console.log("最后执行的");
      };
      let throttled = function() {
        context = this;
        args = arguments;
        let now = +new Date();
        // 下次触发fn剩余的时间
        remaining = wait - (now - previous);
        // 表明我这个定时器执行完了 那么就执行n秒后(好比:3~6秒)的事件操做
        // 若是没有剩余的时间
        if (remaining <= 0) {
          if (timeout) {
            clearTimeout(timeout);
            timeout = null;
          }
          previous = now;
          // 当即执行
          fn.apply(context, args);
        } else if (!timeout) {
          timeout = setTimeout(later, remaining);
        }
      };
      return throttled;
    }
复制代码

效果图:

包含当即执行和非当即执行

有时候咱们想要一种状况就行,想要当即执行不须要再去执行一次,或者想要最后执行一次,不须要当即执行,那咱们对上述作个兼容

实现方式是定义一个options对象,禁止当即执行或者非当即执行

  • immediate:false 表示禁用第一次执行
  • last: false 表示禁用中止触发的回调
function throttle(fn, wait, options) {
      let timeout, remaining, context, args;
      let previous = 0;
      // timeout等于null,表明定时器已经完成
      // 若是没有传options默认为空
      if (!options) {
        options = {}; // 虽然没有声明options, 至关于window.options={}
      }
      let later = function() {
        // previous = +new Date();
        previous = options.immediate == false ? 0 : new Date().getTime(); // +new Date() 等同于:new Date().getTime()
        timeout = null;
        fn.call(context, args);
        console.log("最后执行的");
      };
      let throttled = function() {
        context = this;
        args = arguments;
        let now = +new Date();
        if (!previous && options.immediate === false) {
          previous = now;
        }
        // 下次触发 func 剩余的时间
        remaining = wait - (now - previous);
        // 表明我这个定时器执行完了 那么就执行n秒后(好比:3~6秒)的事件操做
        // 若是没有剩余的时间了
        if (remaining <= 0) {
          if (timeout) {
            clearTimeout(timeout);
            timeout = null;
          }
          previous = now;
          // 当即执行
          fn.apply(context, args);
        } else if (!timeout && options.last !== false) {
          timeout = setTimeout(later, remaining);
        }
      };
      return throttled;
    }
复制代码

demo使用:

search.onkeyup = throttle(getSearchInfo, 3000, { immediate: true, last: false });
复制代码

优化throttle函数

上述例子中咱们使用了闭包,而闭包所引用的变量挺多的,可是一直没有被gc回收,咱们来手动回收下这些变量

function throttle(fn, wait, options) {
      let timeout, remaining, context, args;
      let previous = 0;
      // timeout等于null,表明定时器已经完成
      // 若是没有传options默认为空
      if (!options) {
        options = {}; // 虽然没有声明options, 至关于window.options={}
      }
      let later = function() {
        // previous = +new Date();
        previous = options.immediate == false ? 0 : new Date().getTime(); // +new Date() 等同于:new Date().getTime()
        timeout = null;
        fn.call(context, args);
        if (!timeout) context = args = null;
        console.log("最后执行的");
      };
      let throttled = function() {
        context = this;
        args = arguments;
        let now = +new Date();
        if (!previous && options.immediate === false) {
          previous = now;
        }
        // 下次触发 func 剩余的时间
        remaining = wait - (now - previous);
        // 表明我这个定时器执行完了 那么就执行n秒后(好比:3~6秒)的事件操做
        // 若是没有剩余的时间了
        if (remaining <= 0) {
          if (timeout) {
            clearTimeout(timeout);
            timeout = null;
          }
          previous = now;
          // 当即执行
          fn.apply(context, args);
          if (!timeout) context = args = null;
        } else if (!timeout && options.last !== false) {
          timeout = setTimeout(later, remaining);
        }
      };
      return throttled;
    }
复制代码

取消功能

咱们再拓展个取消功能,取消功能实际就是取消定时器,让它在这一次事件触发中当即执行

function throttle(fn, wait, options) {
      let timeout, remaining, context, args;
      let previous = 0;
      // timeout等于null,表明定时器已经完成
      // 若是没有传options默认为空
      if (!options) {
        options = {}; // 虽然没有声明options, 至关于window.options={}
      }
      let later = function() {
        // previous = +new Date();
        previous = options.immediate == false ? 0 : new Date().getTime(); // +new Date() 等同于:new Date().getTime()
        timeout = null;
        fn.call(context, args);
        if (!timeout) context = args = null;
        console.log("最后执行的");
      };
      let throttled = function() {
        context = this;
        args = arguments;
        let now = +new Date();
        if (!previous && options.immediate === false) {
          previous = now;
        }
        // 下次触发 func 剩余的时间
        remaining = wait - (now - previous);
        // 表明我这个定时器执行完了 那么就执行n秒后(好比:3~6秒)的事件操做
        // 若是没有剩余的时间了
        if (remaining <= 0) {
          if (timeout) {
            clearTimeout(timeout);
            timeout = null;
          }
          previous = now;
          // 当即执行
          fn.apply(context, args);
          if (!timeout) context = args = null;
        } else if (!timeout && options.last !== false) {
          timeout = setTimeout(later, remaining);
        }
      };
      throttled.cancel = function() {
        clearTimeout(timeout);
        timeout = null;
        previous = 0;
      };
      return throttled;
    }
复制代码

到这里咱们的节流函数就基本实现完了,接下来那聊聊防抖函数和节流函数的区别吧

防抖和节流的区别

实际上防抖和节流都是限制一些频繁的事件触发window 的 resize、scroll、mousedown、mousemove、keyup、keydown),但他们仍是有实质性的区别的

  • 防抖是虽然事件持续触发,但只有等事件中止触发后n秒才执行函数(若是你在时间内从新触发事件,那么时间就从新算,这是防抖的特色,能够按照这个特色选择场景)。好比生活中的坐公交,就是必定时间内,若是有人陆续刷卡上车,司机就不会开车。只有别人没刷,司机才开车。

  • 节流是持续触发的时候,每隔n秒执行一次函数好比人的眨眼睛,就是必定时间内眨一次。这是函数节流最形象的解释

总结

防抖函数和节流函数涉及到的知识点不少,他们以接收一个函数为参数,实际就是一个高阶函数,也用到了闭包,this指向,apply等知识点,固然函数的实现是参考大佬的博客,我这里就是作下记录以及总结

相关文章
相关标签/搜索