若依框架中的节流和防抖

节流

/**
 * @description: 节流
 * @param {*} delay
 * @param {*} fn
 * @return {*}
 */
export const throttle = function (delay, fn) {
  let firstTime = true
  let timer = null
  return function () {
    const args = [].slice.apply(arguments)
    if (firstTime) {
      fn.apply(this, args)
      firstTime = false
      return
    }
    if (timer) return
    timer = setTimeout(() => {
      fn.apply(this, args)
      clearTimeout(timer)
      timer = null
    }, delay)
  }
}

防抖

/**
 * @Description: 防抖
 * @param {*} fn 要防抖函数
 * @param {*} wait 延迟毫秒
 * @param {*} immediate
 * @return {*}
 */
export const debounce = (fn, wait, immediate) => {
  let timer
  return function () {
    if (timer) clearTimeout(timer)
    if (immediate) {
      if (!timer) {
        fn.apply(this, arguments)
      }
      timer = setTimeout(() => {
        timer = null
      }, wait)
    } else {
      timer = setTimeout(() => {
        fn.apply(this, arguments)
      }, wait)
    }
  }
}
posted @ 2022-07-22 18:00  iooz  阅读(1511)  评论(0)    收藏  举报