Sometimes its necessary to limit the number of times a function can be fired in an second, minute or hour. If a function does some heavy frontend reflow or repainting or else sends/receives data from server then its better to limit the number of times it can execute in a given amount of time.
JavaScript developers usually use a hack i.e., wrapping a normal function in an debounce function. Debounce function is a wrapper and it decides weather the actual code of the function should be executed or not at a particular given time.
Here is code for creating a debounce function i.e., function call rate limiting wrapper function
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);
};
};
Here is an example of how debounce function controls the call rate of an normal function
In the above example the setTimeout callback was supposed to run after 100ms when button is clicked but debounce functions queues it to execute after 5sec. And any number of calls during queue is cancelled.
Leave a Reply