If I have a function foo
. It receives many calls at a short period of time.
function foo(name) {
console.log(`Hi ${name}, it is now: `, new Date());
}
Delaying consecutive function invocations (debouncing ) is working fine using lodash .
const debouncedFoo = _.debounce(foo, 1000 );
However, my target is to NOT execute this whole fleet of invocations even the timeout (1000
) have elapsed, and consider only the last invocation to be executed .
In other words, if i called debouncedFoo
5 times within 900 ms (which is less than "wait param" 1000ms ), I want foo
to be executed only once which is the last (5ᵗʰ) call .
Reading lodash documentation , I understood that debounce
is overloaded by 3ʳᵈ argument which is options. I used them and the expected behavior does not happen:
// first attempt
const debouncedFoo = _.debounce(foo, 1000, {leading: true} );
// second attempt
const debouncedFoo = _.debounce(foo, 1000, {trailing: false} );