简体   繁体   English

jQuery 中的去抖动功能

[英]Debounce function in jQuery

I'm attempting to debounce a button's input using the jquery debouncing library by Ben Alman.我正在尝试使用 Ben Alman 的 jquery debounce 库对按钮的输入进行 debounce。 http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/ http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/

Currently this is the code that I have.目前这是我拥有的代码。

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

$(".my-btn").click(function() {
    $.debounce(250, foo);
});

The problem is that when I click the button, the function never executes.问题是当我单击按钮时,该函数永远不会执行。 I'm not sure if I've misunderstood something but as far as I can tell, my code matches the example.我不确定我是否误解了某些东西,但据我所知,我的代码与示例相匹配。

I ran into the same issue.我遇到了同样的问题。 The problem is happening because the debounce function returns a new function which isn't being called anywhere.出现问题是因为 debounce 函数返回一个新函数,该函数没有在任何地方被调用。

To fix this, you will have to pass in the debouncing function as a parameter to the jquery click event.要解决此问题,您必须将 debounce 函数作为参数传递给 jquery 单击事件。 Here is the code that you should have.这是您应该拥有的代码。

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

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

You can use it by simply wrapping the function call with a call to callOnce() , eg callOnce(functionThatIsCalledFrequently);您可以通过简单地用callOnce()调用包装函数调用来使用它,例如callOnce(functionThatIsCalledFrequently); or callOnce(function(){ doSomething(); }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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM