JS

JS基础-防抖和节流

2021-11-20  本文已影响0人  wo不是黄蓉
前言

一直以来都有使用防抖和节流函数,但是奈何两个概念太过相似,因此一直理解不清楚,今天专门花时间写了个例子,来感受一波防抖和节流到底有什么区别。

注意点:
     <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        background-color: gray;
      }
      #box,
      #box1 {
        width: 400px;
        height: 400px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #ffffff;
        margin: 0 auto;
        font-size: 80px;
      }
    </style>
  </head>
  <body>
<!--写一个box给其绑定mouseover事件,鼠标移上去就会触发-->
    <div id="box">1</div>
    <div id="box1">1</div>
    <script>
      let count = 1;
      let box = document.getElementById("box");
      let box1 = document.getElementById("box1");
      //debounce相当于是鼠标移上去的时候执行的函数,但是如果带上()就是执行函数,因此我们需要让debounce函数返回一个函数,以供执行真正的操作
      box.onmouseover = debounce(handleMouseOver, 2000);
      box1.onmouseover = debounce(handleMouseOver1, 2000);
      box.onmouseover = throttle(handleMouseOver, 5000);
      function handleMouseOver(e) {
        console.log(234);
        this.style.color = "red";
        box.innerHTML = parseInt(box.innerText) + 1;
      }
      function handleMouseOver1(e) {
        this.style.color = "green";

        box1.innerHTML = parseInt(box1.innerText) + 2;
      }

      //防抖函数
      function debounce(fn, await) {
        let timer = null;
        return function () {
          let args = arguments;
          let context = this;
          clearTimeout(timer);
          console.log(123);
          timer = setTimeout(function () {
            fn.call(context, ...args);
          }, await);
        };
      }

  //节流函数
      function throttle(func, wait) {
        var context, args;
        var previous = 0;
        return function () {
          console.log(123);
          var now = +new Date();
          context = this;
          args = arguments;
          if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
          }
        };
      }
    </script>
  </body>
</html>

2022.3.19补充
节流函数的另一种实现方式:

//使用定时器
function throttle(fn,wait){
  let timer = null;
  return function(){
    let context = this,args = arguments;
    //只有在当前的timer执行完毕销毁之后才会进行下一次的调用
    if(!timer){
      timer = setTimeout(()=>{
        fn.call(context,...args)
      },wait)
    }
  }
}

两者的区别:
防抖函数:在一定时间内执行一个方法多次,只执行最后一次。因为在事件触发会先清理timer,如果时间间隔不到则会被清理掉,只有你的间隔到了之后才会执行,因此前面的函数都会被清理掉。
节流函数:在一定时间内执行一个方法多次,只有第一次生效。因为在事件触发后会先判断timer是否存在,只有不存在的时候才会执行。
相当于防抖是强制清理,节流是不到时间进不了大门。

上一篇下一篇

猜你喜欢

热点阅读