You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现特殊debounce方法:仅在第n次调用时才触发目标函数

实现代码

你给出的示例中对_debounce的调用方式需要稍作调整,_debounce需要先返回一个包装后的函数,再重复调用该包装函数才能在多次调用间共享计数状态,完整实现如下:

const _debounce = (n, func) => {
    // 闭包存储调用次数,不会污染外部作用域
    let callCount = 0
    return function (...args) {
        callCount++
        if (callCount === n) {
            // 保留this指向和参数传递
            func.apply(this, args)
            // 执行后重置计数,开启下一轮统计
            callCount = 0
        }
    }
}

const originFun = () => {
  console.log('hit')
}

// 先获取包装后的调用函数,再重复调用
const _call = _debounce(2, originFun)

_call() // originFun 不执行
_call() // 打印 hit
_call() // originFun 不执行
_call() // 打印 hit

实现说明

核心是通过闭包保存计数器状态,每次调用包装函数时计数器自增,当计数器等于传入的阈值n时执行目标函数,同时重置计数器开启下一轮计数,完全匹配你需要的执行逻辑。

内容的提问来源于stack exchange,提问作者eGluZl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 12:27:03