防抖(debounce)与节流(throttle)

1.防抖(debounce)

  --函数防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

  --防抖应用场景--------连续的事件,只需触发一次回调的场景   将多次函数的执行变成一次函数的执行

    1.搜索框搜索输入。只需用户最后一次输入完,再发送请求

    2.手机号、邮箱验证输入检测

    3.窗口大小Resize。只需窗口调整完成后,计算窗口大小。防止重复渲染

            // 函数防抖
    const debounce = (func,time) => {
      let timer;
      return () => {
        clearTimeout(timer);
        timer = setTimeout(func, time);
      };
    }; 

          // 第一不执行延迟 后面会照常执行
    function debounce(func,time,triggleNow) {
      var timer = null

          var debounced = function(){
            var _self = this,
                args = arguments
          }
          if(timer) {
            clearTimeout(timer)
          }
          if(trigilleNow) {
            var exec = !timer
            timer = setTimeout(function () {
              timer =null
            },time)

            if(exec) {
              fn.apply(_self,args)
            }
          }else {
            timer = setTimeout(function(){
              fn.apply(_self,args);
            },timer)
          }

        debounced.remove = function () {
          clearTimeout(timer)
          timer = null
        }
    }

 

2.节流(throttle)

  --函数节流,就是限制一个函数在一定时间内只能执行一次。 例如单位时间内触发了30次事件 也只会执行第一次 后面不执行

  --节流的应用场景

    1.滚动加载,加载更多或滚到底部监听

    2.搜索框,搜索联想功能

    3.高频点击提交,表单重复提交

          //节流
  function throttle (func,time) {
      //  定义起始时间
      let start = 0
      return  function () {
        // 定义函数触发当前时间
        let now = new Date()
        let that = this
        let arg = arguments
        // 如果距离上次运行时间超过time 执行此次操作
        if(now - start > time){
          func.call(that,arg)
          // 重置时间起始
          start = now
        }
      }
    }                

 

posted on 2021-05-09 12:25  贲风  阅读(420)  评论(0)    收藏  举报