Reputation: 357
I'm trying to call a debounced function from setInterval but for some reason it doesn't works and the function doesn't invoke, any idea why?
const _ = require('lodash');
const debouncedFunction = _.debounce(() => console.log('test'), 4000);
setInterval(() => {
console.log('tick');
debouncedFunction();
}, 1000);
It is worth to mention that if I replace the setInterval with setTimeout it works
https://repl.it/@ShahafMango/CheeryKaleidoscopicOffice
Upvotes: 0
Views: 2875
Reputation: 191976
The purpose of wrapping a function with debounce is to delay the execution of the function as long as it's called repeatedly. The wait
parameter states the time that should elapse after the last call of the debounced function, before the inner function is invoked. If the the interval calls the function once every 1000ms, and the wait is 4000ms, the wrapped function would never be called.
Changing the interval to something less than 1000 will call the function (and probably defeat the original purpose of wrapping with debounce):
const debouncedFunction = _.debounce(() => console.log('test'), 500);
setInterval(() => {
console.log('tick');
debouncedFunction();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
If you want to limit the function to work once every 4000ms use _.throttle()
instead. Throttle will limit the invocation of the inner function to once per the wait time, no matter how many times the wrapped function was called.
const debouncedFunction = _.throttle(() => console.log('test'), 4000);
setInterval(() => {
console.log('tick');
debouncedFunction();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Upvotes: 2