若依框架中的节流和防抖

节流

/**
 * @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 @   iooz  阅读(1253)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示