jQuery中的Debounce功能

Gun*_*her 24 javascript jquery debouncing

我试图使用Ben Alman的jquery debouncing库去除按钮的输入. http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/

目前这是我的代码.

function foo() {
    console.log("It works!")
};

$(".my-btn").click(function() {
    $.debounce(250, foo);
});
Run Code Online (Sandbox Code Playgroud)

问题是,当我单击按钮时,该功能永远不会执行.我不确定我是否误解了一些东西但据我所知,我的代码与示例匹配.

小智 49

我遇到了同样的问题.问题正在发生,因为debounce函数返回一个不在任何地方调用的新函数.

要解决此问题,您必须将debouncing函数作为参数传递给jquery click事件.这是您应该拥有的代码.

$(".my-btn").click($.debounce(250, function(e) {
    console.log("It works!");
}));
Run Code Online (Sandbox Code Playgroud)

  • 或者`$(".my-btn").点击($ .debounce(250,foo))`当然. (8认同)
  • 这是什么版本的jquery? (8认同)

isa*_*pir 10

就我而言,我需要对不是由 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;
}
Run Code Online (Sandbox Code Playgroud)