防抖和节流

57 阅读1分钟

节流

所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数

    function throttle(fn,time){ 
      let startTime = 0
      return function() {
        let now =Date.now()
        if(now-startTime>time){ 
          fn()
          startTime = now
        }
      }
    }

lodash内有写好的节流函数,使用前下载引入然后调用即可 _.throttle(fn,time)

节流类似于每天早上六点的闹钟,间隔相同的时间就会执行一次。

防抖

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

    function debounce(fn,time){ 
      let timerId=null
      return function(){ 
        clearTimeout(timerId)
        timerId = setTimeout(fn,time)
      }
    }

lodash内有写好的节流函数,使用前下载引入然后调用即可 _.debounce(fn,time)

防抖类似于游戏里面的回城,被打断就要重新计时