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 小时前
为啥Agent在coding表现这么好,但是在别的领域就是差的不少?
前端·agent·ai编程
李妍.2 小时前
02Numpy基础(上)
开发语言·python
TheBestRucy2 小时前
Python 九阳神功之贰:面向对象(下)
开发语言·python
AI_小站3 小时前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
felixking3 小时前
C++20 协程
开发语言·c++·协程
鱼与宇4 小时前
前端Web(html+css+js+vue3)
前端
Zane1994125 小时前
CAS 与原子类:Java 如何实现无锁编程
java·开发语言
码农颜6 小时前
6.3 主函数流程剖析
开发语言·php
雪芽蓝域zzs6 小时前
(六)打包优化 + Nginx 部署完整配置 + 项目收尾
前端·vue.js
TheBestRucy6 小时前
Python 九阳神功:从零筑基到线程飞升
服务器·开发语言·网络·人工智能·python