Javascript jQuery 中的去抖动功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27787768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:40:19  来源:igfitidea点击:

Debounce function in jQuery

javascriptjquerydebouncing

提问by Gunther

I'm attempting to debounce a button's input using the jquery debouncing library by Ben Alman. http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/

我正在尝试使用 Ben Alman 的 jquery 去抖动库对按钮的输入进行去抖动。 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.

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

回答by Geoff

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. Here is the code that you should have.

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

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