JS 防抖封装方法

防抖封装方法:

javascript 复制代码
/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在,重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}
相关推荐
2分钟速写快排6 小时前
孔乙己的茴字有多少种写法?|AI 对话实时通信的三种实现
前端·javascript·github
Penge6668 小时前
JavaScript:BOM 详解
前端
Penge6669 小时前
Vite vs Webpack:前端构建工具原理与实战
前端
Penge6669 小时前
前端包管理工具:npm、Yarn、pnpm 快速入门
前端
Penge6669 小时前
Sass 了解
前端
Penge6669 小时前
Webpack 打包从 0 到 1 实战笔记
前端
大可不必了9 小时前
03 函数定义和调用
开发语言·python
I_belong_to_jesus9 小时前
C++关于分支预测的优化1
开发语言·c++·算法
Penge66610 小时前
Webpack 入门:是什么、为什么需要、怎么使用?
前端
Penge66610 小时前
Ant Design(Antd)了解
前端