如何检测_.debounce防抖函数是否处于待执行状态?
检测_.debounce防抖函数是否处于待执行状态的方法
默认情况下,Lodash的_.debounce确实只公开了flush和cancel这两个官方方法,没有直接提供检测待执行状态的API,但我们可以通过两种方式实现这个需求:
1. 自定义包装函数(推荐,无内部依赖)
我们可以自己写一个轻量的包装层,通过闭包跟踪防抖函数的执行状态,这种方式不依赖Lodash的内部实现,兼容性和稳定性都更好:
function createTrackedDebounce(func, wait) { let isPending = false; // 包装原防抖函数,执行时同步状态 const debounced = _.debounce((...args) => { isPending = false; func(...args); }, wait); // 重写cancel方法,确保状态同步 const originalCancel = debounced.cancel; debounced.cancel = () => { originalCancel(); isPending = false; }; // 重写flush方法,确保状态同步 const originalFlush = debounced.flush; debounced.flush = () => { originalFlush(); isPending = false; }; // 创建带状态标记的包装函数 const wrappedFunc = (...args) => { isPending = true; return debounced.apply(this, args); }; // 添加状态检测方法 wrappedFunc.isPending = () => isPending; // 暴露原有的官方方法 wrappedFunc.flush = debounced.flush; wrappedFunc.cancel = debounced.cancel; return wrappedFunc; } // 使用示例 const log = () => console.log('防抖函数执行'); const debouncedLog = createTrackedDebounce(log, 2000); debouncedLog(); console.log(debouncedLog.isPending()); // 输出 true setTimeout(() => { console.log(debouncedLog.isPending()); // 输出 false(函数已执行) }, 2100); // 测试cancel逻辑 debouncedLog(); console.log(debouncedLog.isPending()); // 输出 true debouncedLog.cancel(); console.log(debouncedLog.isPending()); // 输出 false
2. 访问Lodash内部属性(不推荐,依赖实现)
如果你能接受依赖Lodash的内部实现(风险提示:这可能在Lodash版本更新时失效),可以直接访问防抖函数的内部定时器属性。在多数Lodash版本中,防抖函数会有一个_timeout属性——当存在待执行任务时,这个属性会指向当前的定时器ID,否则为null:
const debouncedFunc = _.debounce(() => {}, 1000); debouncedFunc(); // 检测是否处于待执行状态 console.log(!!debouncedFunc._timeout); // 输出 true setTimeout(() => { console.log(!!debouncedFunc._timeout); // 输出 false }, 1100);
⚠️ 注意:这种方法不推荐,因为Lodash的内部属性不属于公开API,未来版本可能会修改属性名或实现逻辑,导致你的代码突然失效。
总结来说,自定义包装函数的方式是更可靠的选择,它不会依赖Lodash的内部细节,能保证代码在不同版本的Lodash中都正常工作。
内容的提问来源于stack exchange,提问作者Queue Overflow
相关产品推荐
相关产品推荐

