Sunday, May 19, 2024
56
rated 0 times [  60] [ 4]  / answers: 1 / hits: 49437  / 9 Years ago, thu, march 12, 2015, 12:00:00

I create a debounced version of a function with underscore:



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


Once debouncedThing is called...



debouncedThing();


...is there any way to cancel it, during the wait period before it actually executes?


More From » underscore.js

 Answers
26

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;

[#67458] Wednesday, March 11, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyterryp

Total Points: 290
Total Questions: 92
Total Answers: 95

Location: Montenegro
Member since Sun, May 7, 2023
1 Year ago
;