防抖和节流函数记录

165 阅读1分钟

节流:规定时间内只执行一次 防抖:规定时间内执行最后一次


 /**
     * @desc 函数节流
     * @param func 函数
     * @param wait 延迟执行毫秒数
     */
    throttle(func, wait) {
      let timeout
      return function () {
        let context = this
        let args = arguments
        if (!timeout) {
          timeout = setTimeout(() => {
            timeout = null
          }, wait)
          func.apply(context, args)
        }
      }
    },
    /**
     * @desc 函数防抖
     * @param func 函数
     * @param wait 延迟执行毫秒数
     * @param immediate true 表立即执行,false 表非立即执行
     */
    debounce(func, wait, immediate) {
      let timeout

      return function () {
        let context = this
        let args = arguments

        if (timeout) clearTimeout(timeout)
        if (immediate) {
          var callNow = !timeout
          timeout = setTimeout(() => {
            timeout = null
          }, wait)
          if (callNow) func.apply(context, args)
        } else {
          timeout = setTimeout(function () {
            func.apply(context, args)
          }, wait)
        }
      }
    },

本文转自:www.jianshu.com/p/c8b86b09d…