节流和防抖

97 阅读1分钟

事件频发没触发可能造成的问题

  • 一些浏览器事件:window.onresize、window.mousemove等,触发频率搞会造成浏览器性能问题
  • 如果向后台频繁发送请求,会对服务器造成不必要的压力

如何限制事件处理函数频繁调用

  • 节流
  • 防抖

image.png

函数节流(throttle)

在函数需要频繁触发时:函数执行一次后,只有大于设定的执行周期后才会进行第二次执行。适合多次时间按时间做平均分配触发

应用场景:窗口调整(resize)、页面滚动(scroll)、DOM元素的拖拽功能实现(mousemove)、抢购疯狂点击(click)

  // 防抖:只执行最后一次
  // 节流:控制高频事件执行次数
  let flag = true;
  window.onscroll = throttle(function() {
    console.log('233');
  },300)
  function throttle(fn, delay) {
    let flag = true;
    return function() {
      if(flag) {
        setTimeout(() => {
          fn.call(this);
          flag = true;
        },delay)
      }
      flag = false;
    }
  }

函数防抖(debounce)

在函数需要频繁触发时:在规定时间内只让最后一次生效,适合多次时间一次响应的情况

应用场景:输入框实时搜索联想(keyup/input)

  let myInput = document.querySelector('input');
  let timer = null;
  myInput.oninput = function() {
    if(timer != null) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      console.log(this.value);
    },800)
  }

防抖函数封装

  let myInput = document.querySelector("input");

  myInput.oninput = debounce(function() {
    console.log(this.value);
  }, 800)
  function debounce(fn, delay) {
    let timer = null;
    return function () {
      if (timer != null) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        fn.apply(this, arguments);
      }, delay);
    };
  }