使用定时器实现节流防抖

1,016 阅读1分钟

节流防抖

就是限制函数的执行次数

1.防抖(在一定的时间间隔中,将多次触发变成一次触发)

用户频繁操作,但是只需要最后一次事件的操作

<script>
    const input = document.querySelector("#input");
    // 模拟ajax请求,业务逻辑代码
    function ajax() {
      console.log(input.value);
    }
​
    // 防抖,采用闭包函数
    function timer(fn, de) {
      // 控制定时器
      let times = null;
      return function () {
        if (times != null) {
          clearTimeout(times);
        }
        times = setTimeout(function () {
          //业务逻辑
          fn();
        }, de);
      };
    }
​
    // input.addEventListener("keyup", timer(ajax, 500));
    input.oninput = timer(ajax, 500);
  </script>

2.节流(连续触发事件,但是在具体的间隔秒数中只执行一次)

不管触发多少次事件,都只在固定的时间间隔执行事件处理函数

//逻辑代码
// 通过窗口的大小来控制body的背景色
    function colors() {
      let r = Math.floor(Math.random() * 255);
      let g = Math.floor(Math.random() * 255);
      let b = Math.floor(Math.random() * 255);
      document.body.style.backgroundColor = `rgb(${r},${g},${b})`;
    }
​
    // 节流
​
    // 节流代码
    function jieliu(callback) {
      let t = null;
      return function () {
        if (t) {
          return;
        }
        t = setTimeout(() => {
          callback();
          t = null;
        }, 2000);
      };
    }
    //   window中的方法,窗口大小改变会触发
    window.onresize = jieliu(colors);
                   ---------------------------------------------------------持续更新的第五天