防抖和节流理解和实现

126 阅读1分钟

防抖

所谓防抖,是指在事件触发后n秒内只执行一次,如果在这n秒内再次触发,则会重新计算时间。

  • 应用场景
  1. 按钮提交场景:防止多次点击,多次提交,只提交最后一次点击
  2. 搜索框联想场景:防止联想发生请求,只发送最后一次请求
  • 实现方案
    • 函数自接调用
    function debounce (fn, time) {
        if(this.timeout) clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
            fn()
        }, time)
    }
    
    • 闭包函数
    function debounce(fnc, time) {
        let timeout
        let _this = this
        return function () {
            if (timeout) clearTimeout(timeout)
            timeout = setTimeout(()=> {
                fnc.apply(_this)
            }, time)
    
        }
    }
    

节流

所谓节流,是指在规定的时间内事件只执行一次,如果在规定时间内多次触发,事件也只执行一次,并且时间不会叠加延迟

  • 应用场景
  1. 拖拽场景:固定时间内只执行一次,防止高频次触发执行
  2. 缩放场景:监听浏览器resize
  • 实现方案

    • 使用时间戳
    function throttle(func, wait) {
      let context, args;
      let previous = 0;
    
      return function () {
        let now = +new Date();
        context = this;
        args = arguments;
        if (now - previous > wait) {
          func.apply(context, args);
          previous = now;
        }
      }
    }
    
    • 使用定时器实现
    function throttle(func, wait) {
      let timeout;
      return function () {
        const context = this;
        const args = arguments;
        if (!timeout) {
          timeout = setTimeout(function () {
            timeout = null;
            func.apply(context, args)
          }, wait)
        }
    
      }
    }