防抖

主要是为了避免在频繁的操作中导致页面的卡顿,因此将短时间内多次的操作合并为一次。

const debounce = (func, wait=50) => {
    let timer = 0
    let f = function (...args) {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            func.apply(this, args)
        })
    }
    return f
}

但是,有时候需要需要立刻执行,因此做一下修改

const debounce = (func, wait=50, immediate=true) => {
    let timer = 0
    let context = null
    let args = null

    const later = () => {
      setTimeout(() => {
          timer = null
          if (!immediate) {
              func.apply(context, args)
              context = null
              args = null
          }
      }, wait)
    }

    let f = function (...params) {
        if (timer) {
            clearTimeout(timer)
            timer = later()
        } else {
            timer = later()
            if (immediate) {
                func.apply(context, args)
            } else {
                context = this
                args = params
            }
        }
    }
    return f
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容