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

use*_*947 29 javascript underscore.js

我用下划线创建了一个去抖动函数:

var debouncedThing = _.debounce(thing, 1000);
Run Code Online (Sandbox Code Playgroud)

一旦debouncedThing被调用...

debouncedThing();
Run Code Online (Sandbox Code Playgroud)

...有没有办法取消它,在实际执行之前的等待期间?

小智 46

如果你使用最后一个版本的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()
Run Code Online (Sandbox Code Playgroud)

另一个解决方案是带有标志:

// 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;
Run Code Online (Sandbox Code Playgroud)


S..*_*S.. 6

对于其他使用带有状态钩子的 React 的人。将 debounce 事件包装在 ref 中,然后在其他地方访问:

const [textInputValue, setTextInputValue] = React.useState<string>('')
    
const debouncedSearch = React.useRef(
    debounce((textInputValue) => {
        performSearch(textInputValue)
    }, 300),
).current

React.useEffect(() => {
    // cancel any previous debounce action (so that a slower - but later - request doesn't overtake a newer but faster request)
    debouncedSearch.cancel()
    if (textInputValue !== '') {
        debouncedSearch(textInputValue)
    }
}, [textInputValue])
Run Code Online (Sandbox Code Playgroud)


Ste*_*uel 5

文档(我现在正在查看 1.9.1)说你应该能够执行以下操作:

var fn = () => { console.log('run'); };
var db = _.debounce(fn, 1000);
db();
db.cancel();
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/underscore@1.13.6/underscore-umd-min.js"></script>
Run Code Online (Sandbox Code Playgroud)

这将完成OP想做的事情(以及我想做的事情)。它不会打印控制台消息。