最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - debounce with ignoring all calls except the last using lodash - Stack Overflow

programmeradmin3浏览0评论

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} );

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} );
Share Improve this question asked Nov 10, 2017 at 2:53 Abdennour TOUMIAbdennour TOUMI 93.2k42 gold badges267 silver badges269 bronze badges 3
  • 1 Isn't it thottling then that you want? lodash.com/docs/#throttle – Kaiido Commented Nov 10, 2017 at 4:31
  • 2 It's been a while but for anyone else (like me) stumbling across this - something that can be overlooked sometimes is accidentally recreating the debounced function on every state change. – AndyO Commented Dec 21, 2019 at 12:47
  • 3 Glorious comment @AndyO . This was true in my case - I was using debounce inside a react component. Re-renders were creating multiple instances of debounce. Fixed by moving function out of the component. You saviour ✌️
发布评论

评论列表(0)

  1. 暂无评论