如何在调用之后和执行之前取消去抖动函数? [英] How to cancel a debounced function after it is called and before it executes?
本文介绍了如何在调用之后和执行之前取消去抖动函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用下划线创建了一个去抖动函数:
I create a debounced version of a function with underscore:
var debouncedThing = _.debounce(thing, 1000);
调用debouncedThing后......
Once debouncedThing is called...
debouncedThing();
...有没有办法在实际执行之前的等待期间取消它? / p>
...is there any way to cancel it, during the wait period before it actually executes?
推荐答案
如果您使用最新版本的lodash,您可以这样做:
If you use the last version of lodash you can simply do:
// create debounce
const debouncedThing = _.debounce(thing, 1000);
// execute debounce, it will wait one second before executing thing
debouncedThing();
// will cancel the execution of thing if executed before 1 second
debouncedThing.cancel()
另一个解决方案是带标志:
Another solution is with a flag:
// create the flag
let executeThing = true;
const thing = () => {
// use flag to allow execution cancelling
if (!executeThing) return false;
...
};
// create debounce
const debouncedThing = _.debounce(thing, 1000);
// execute debounce, it will wait one second before executing thing
debouncedThing();
// it will prevent to execute thing content
executeThing = false;
这篇关于如何在调用之后和执行之前取消去抖动函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文