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

javascript - Cancel lodash's debounce, without invoking the function - Stack Overflow

programmeradmin0浏览0评论

My question is, if there is a way to cancel lodash's debounce, without invoking the function to debounce. The .cancel() from lodash still invokes the function.

Maybe I am looking for the wrong approach. If so, is there any other solution for something like this?

Thank you in advance.

My question is, if there is a way to cancel lodash's debounce, without invoking the function to debounce. The .cancel() from lodash still invokes the function.

Maybe I am looking for the wrong approach. If so, is there any other solution for something like this?

Thank you in advance.

Share Improve this question asked Jul 31, 2020 at 14:00 philmanphilman 1593 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Calling the cancel method on the debounced function does not invoke it, unless it is on the trailing edge of the timeout. You can use the trailing option to configure this. Docs

const fn1 = () => console.log('Called 1');
const fn2 = () => console.log('Called 2');
const fn3 = () => console.log('Called 3');

const debouncedFn1 = _.debounce(fn1, 1000);
const debouncedFn2 = _.debounce(fn2, 1000);
const debouncedFn3 = _.debounce(fn3, 1000, { trailing: false });

// Will not log
debouncedFn1();
setTimeout(debouncedFn1.cancel, 200);

// Will log
debouncedFn2();
setTimeout(debouncedFn2.cancel, 1000);

// Will not log
debouncedFn3();
setTimeout(debouncedFn3.cancel, 1000);
<script src="https://cdn.jsdelivr/npm/[email protected]/lodash.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论