In my case I needed to debounce a function call that was not generated directly by a jQuery event handler, and the fact that $.debounce() returns a function made it impossible to use, so I wrote a simple function called callOnce()
that does the same thing as Debounce, but can be used anywhere.
You can use it by simply wrapping the function call with a call to callOnce()
, e.g. callOnce(functionThatIsCalledFrequently);
or callOnce(function(){ doSomething(); }
/**
* calls the function func once within the within time window.
* this is a debounce function which actually calls the func as
* opposed to returning a function that would call func.
*
* @param func the function to call
* @param within the time window in milliseconds, defaults to 300
* @param timerId an optional key, defaults to func
*/
function callOnce(func, within=300, timerId=null){
window.callOnceTimers = window.callOnceTimers || {};
if (timerId == null)
timerId = func;
var timer = window.callOnceTimers[timerId];
clearTimeout(timer);
timer = setTimeout(() => func(), within);
window.callOnceTimers[timerId] = timer;
}