gpt4 book ai didi

javascript - 如何在调用后和执行前取消去抖函数?

转载 作者:行者123 更新时间:2023-12-02 23:16:11 25 4
gpt4 key购买 nike

我创建了一个带有下划线的函数的去抖版本:

var debouncedThing = _.debounce(thing, 1000);

一旦 debouncedThing 被调用...

debouncedThing();

...有什么方法可以在实际执行之前的等待期间取消它吗?

最佳答案

如果您使用最新版本的 lodash,您可以简单地执行以下操作:

// 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()

另一个解决方案是使用标志:

// 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;

关于javascript - 如何在调用后和执行前取消去抖函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29012922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com