在我的例子中,我需要去抖动一个不是由 jQuery 事件处理程序直接生成的函数调用,而 $.debounce() 返回一个函数的事实使它无法使用,所以我写了一个简单的函数,调用callOnce()它来做同样的事情像 Debounce 一样,但可以在任何地方使用。
您可以通过简单地通过调用来包装函数调用来使用它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;
}