I understand that debounce
in Undercore.js returns a function that will postpone its execution until the wait time is over.
My question is, is there an advantage of using debounce
over the regular setTimeout
function in vanilla Javascript? Don't they both work the same?
They are very different and used in completely different cases.
_.debounce
returns a function
, setTimeout
returns an id
which you can use to cancel the timeOut.
No matter how many times you call the function which is returned by _.debounce, it will run only once in the given time frame.
var log_once = _.debounce(log, 5000);
function log() {
console.log('prints');
}
log_once();
log_once();
log_once();
log_once();
log_once();
var id = setTimeout(function() {
console.log('hello');
}, 3000);
clearTimeout(id);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>