在我的情况下,我需要对不是由 jQuery 事件处理程序直接生成的函数调用进行去抖动,并且 $.debounce() 返回一个函数的事实使其无法使用,因此我编写了一个名为的简单函数callOnce()
,它的作用相同像去抖动一样的东西,但可以在任何地方使用。
您可以通过简单地使用调用来包装函数调用来使用它callOnce()
,例如callOnce(functionThatIsCalledFrequently);
或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;
}