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

查看:950
本文介绍了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).

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

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中,我相信:

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

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

code> s.search()通过输入到一个输入框,如果我非常快速地输入乱码,控制台打印每个键按下搜索请求,所以很多次第二 - 表明它没有被去抖动。

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.

任何想法我做错了什么?

Any ideas what's I'm doing wrong?

推荐答案

code> _。debounce 创建一个函数,用于去除传递给它的函数。你的 s.search 函数是在每次调用 _。debounce s.search 。每次都创建一个全新的函数,所以没有什么可以去反弹。

_.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() {
  return console.log("making search request");
};

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

s.search();

s.search();

s.search();

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

// 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天全站免登陆