落落落洛克

超详细由浅到深实现防抖和节流(内附笔记)

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

防抖函数debounce

比如我们的「百度搜索」,搜索的时候有关键字的提醒,关键字的来源来自于客户端向服务端请求得到的数据,我们通过「keyup事件」去监听触发请求,如果返回值的搜索key已经不是搜索框现在的值,就丢弃掉这次返回,于是我们提出这样一个「优化需求」「触发事件,但是我一定在事件触发n秒后才执行,如果你在一个事件触发的n秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行」那么我们来动手实现我们的「第一版」的防抖函数吧:

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

第一版代码已经实现了,我们来写个demo验证下吧:

<!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,那么接下来我们来完善我们的第二版代码吧:

「第二版本的防抖函数」

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等知识点,当然函数的实现是参考大佬的博客,我这里就是做下记录以及总结

前端学习笔记????

最近花了点时间把笔记整理到语雀上了,方便同学们阅读:公众号回复笔记或者简历

最后

1.看到这里了就点个在看支持下吧,你的「点赞,在看」是我创作的动力。

2.关注公众号前端壹栈,回复「1」加入前端交流群!「在这里有好多前端开发者,会讨论前端知识,互相学习」!

3.也可添加公众号【前端壹栈】,一起成长

posted on 2020-12-19 01:32  落落落洛克  阅读(29)  评论(0编辑  收藏  举报

导航