标签:setTimeout Option maxWait debounce Javascript maxTimer timer Extending null
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 };
标签:setTimeout,Option,maxWait,debounce,Javascript,maxTimer,timer,Extending,null 来源: https://www.cnblogs.com/Answer1215/p/16128394.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。