[Javascript] Extending debounce with a maxWait Option
This lessons builds on Build lodash.debounce from scratch to add support for one of its more interesting options: maxWait
. The maxWait
option ensures that a debounced method is deferred no longer than the time specified. This is helpful if we need to respond to a long running interaction while it's still in progress.
In this lesson we'll demonstrate how continuously typing into a debounced input field prevents us from logging any input at all. We'll add a maxWait
option as a third parameter to our debounce
function and set it up using an additional setTimeout
call.
Essentially maxWait
works by adding a second timer which will fire in the case that the normal debounce timer does not get called. We avoid unnecessarily triggering our debounced function by calling clearTimeout
in both of our setTimeout
functions to clear out whichever timer didn't just fire. We also need to set the maxTimer
variable to null
to tell our function it's safe to start a new maxWait timer each time either timer fires.
Notes
setTimeout
returns a timer ID not the actual timer object itself, which is why we have tonull
it out after we already callclearTimeout
- If you don't
null
outmaxTimer
in your original timer, the maxWait timer will stop triggering after the debounce timer is called the first time. I learned that one the hard way when I first recorded this video.
const debouncedLog = debounce(log, 4000, { maxWait: 1000 });
debouncedLog("zhen");
function debounce(fn, wait, { maxWait } = {}) { let timer, maxTimer; return (...args) => { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { clearTimeout(maxTimer); fn.apply(null, args); }, wait); if (maxWait && !maxTimer) { maxTimer = setTimeout(() => { clearTimeout(timer); maxTimer = null; fn.apply(null, args); }, maxWait); } }; } module.exports = { debounce };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-04-11 [RxJS] Extend Promises by Adding Custom Behavior
2019-04-11 [Algorithm] Binary tree: Level Order Traversal
2019-04-11 [SSH] Intro to SSH command
2018-04-11 [Tailwind] Extending Tailwind with Responsive Custom Utility Classes
2018-04-11 [Tailwind] Control What Variations are Generated for Each Utility Class Module in Tailwind
2016-04-11 [RxJS] Creation operator: of()