_.debounce leading and trailing configuration change in lodash 4.x
0 reputation · 06 Jan 2023, 04:44 UTC
0 reputation · 06 Jan 2023, 04:44 UTC
_.debounce in lodash 4.x supports options.leading and options.trailing to control invocation on the leading and trailing edges of the wait window.
The documented interaction is that a leading-edge invocation can cancel a pending trailing-edge invocation within the same wait period. This creates a compatibility boundary when moving from a leading-only or trailing-only debounce pattern to a combined leading:true, trailing:true configuration.
The goal is to clarify the expected invocation semantics for the combined configuration under repeated calls within the wait window, and how that impacts migration decisions.
What is the defined invocation count for a debounced function with leading:true and trailing:true when it is called twice within the wait interval? Does lodash 4.x guarantee a trailing call after a leading call if no further invocations occur during the wait? How does the leading-triggered cancellation of a pending trailing call affect compatibility when switching debounce patterns?
With {leading:true, trailing:true} a debounced function invoked twice within the wait window produces exactly two calls: the leading‑edge call from the first invocation and a trailing‑edge call that fires after the wait period following the second invocation. If the function is invoked only once, you still get two calls – an immediate leading call and a guaranteed trailing call after the wait.
The leading edge runs immediately on the first call and starts a trailing timer. Each subsequent call resets that timer; if another call occurs before the timer expires, the pending trailing invocation is cancelled and a new timer begins from that call. Therefore:
wait → leading from call 1, trailing from call 2.wait (no cancellation).When migrating from a leading‑only or trailing‑only debounce to the combined configuration, note that the leading edge can cancel a pending trailing call that would have occurred in the pure trailing‑only case. This can reduce the number of trailing invocations observed for bursty call patterns.
npm i lodash@4.17.21).const _ = require('lodash');
let count = 0;
const debounced = _.debounce(() => { console.log(Date.now(), ++count); }, 100, {leading:true, trailing:true});
// Scenario A: two calls within wait
debounced();
setTimeout(() => debounced(), 50);
setTimeout(() => { console.log('--- end A ---'); }, 200);
// Scenario B: single call
debounced();
setTimeout(() => { console.log('--- end B ---'); }, 200);
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.