Lodash Debounce 不去抖动 [英] Lodash Debounce not debouncing

查看:33
本文介绍了Lodash Debounce 不去抖动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Lodash 去抖动一个函数,当它调用该函数时,它不会似乎根本没有消除它.我的问题似乎与我在其他地方看到的错误不同 在 SO 或 Google 上(通常,它们不会调用 _.debounce 返回的函数).

I'm trying to debounce a function using Lodash, and while it's invoking the function, it doesn't seem to debounce it at all. My issue doesn't seem to be the same mistake as what I've seen elsewhere on SO or Google (generally, that they're not invoking the function that _.debounce returns).

我目前的超级简单实现如下(在 Angular 中使用 CoffeeScript):

My currently super-simple implementation is as follows (in Angular with CoffeeScript):

  s.search = -> _.debounce( s._makeSearchRequest, 1000 )()

  s._makeSearchRequest = -> console.log("making search request")

在 JS 中,我相信是:

In JS, I believe that's:

  s.search = function() { _.debounce( s._makeSearchRequest, 1000 )() }

  s._makeSearchRequest = function() { console.log("making search request") }

我通过在输入框中键入内容来运行 s.search(),如果我非常快地键入乱码,控制台会在每次按键时打印出make search request",每次如此多次第二 - 表明它根本没有去抖动.

I run s.search() by typing into an input box, and if I type gibberish very quickly, the console prints out "making search request" on every key press, so many times per second -- indicating that it hasn't been debounced at all.

知道我做错了什么吗?

推荐答案

_.debounce 创建 一个函数,用于对传入的函数进行去抖动.你的 s.search 函数所做的是每次 s.search 被调用时重新调用 _.debounce.这每次都会创建一个全新的函数,所以没有什么可以去抖动的.

_.debounce creates a function that debounces the function that's passed into it. What your s.search function is doing is calling _.debounce all over again every time s.search is called. This creates a whole new function every time, so there's nothing to debounce.

所以解决办法是去掉箭头和多余的一对括号,并确保在访问之前定义了s._makeSearchRequest:

So the solution is to remove the arrow and the extra pair of parentheses, and make sure that s._makeSearchRequest is defined before you access it:

s._makeSearchRequest = -> console.log("making search request")

s.search = _.debounce( s._makeSearchRequest, 1000 )

示例(使用 JavaScript):

Example (using JavaScript):

var s;

s = {};

s._makeSearchRequest = function(q) {
  return console.log("making search request: " + q);
};

s.search = _.debounce(s._makeSearchRequest, 1000);

// call s.search three times in a row
s.search(1);
s.search(2);
s.search(3);

// call s.search after 500 ms
setTimeout(s.search, 500, 4);

// call s.search after 3 seconds
setTimeout(s.search, 3000, 5);

// timer to show passage of time
var i = 0;
var t = setInterval(function () {
    i += 1;
    console.log(i + " seconds elapsed");
    if (i > 5) { clearInterval(t); }
}, 1000);

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js"></script>

这篇关于Lodash Debounce 不去抖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆