Reputation: 3164
I have the following debounce function and I need to be able to cancel the debounce by calling clearTimeout(timeout);
within the scope of the debounce
function. I cannot use a library for this.
Here is my code:
var utils = (function(){
return {
debounce: function(func, wait, immediate){
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
}
})();
I want to be able to do something like this but again I cannot figure it out.
var deb = utils.debounce(function(){ console.log("do something"); }, 500);
$(document).on('keyup', '#myId', deb);
deb.cancel(); //this cancel call clears the timeout variable in the debounce function.
Upvotes: 0
Views: 508
Reputation: 138257
Add the cancel function as a property to the returned function:
const utils = (function(){
return {
debounce: function(func, wait, immediate) {
let timeout;
const fn = function() {
const context = this, args = arguments;
const later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
return Object.assign(fn, {
clear() { clearTimeout(timeout); }
});
}
}
})();
Upvotes: 4