lodash debounce not working in anonymous function

lodash debounce not working react
lodash debounce example react
lodash debounce not debouncing
vue lodash debounce not working
$.debounce is not a function
lodash debounce arrow function
lodash debounce not working angular
javascript debounce es6

Hello I cannot seem to figure out why the debounce function works as expected when passed directly to a keyup event; but it does not work if I wrap it inside an anonymous function.

I have fiddle of the problem: http://jsfiddle.net/6hg95/1/

EDIT: Added all the things I tried.

HTML

<input id='anonFunction'/>
<input id='noReturnAnonFunction'/>
<input id='exeDebouncedFunc'/>
<input id='function'/>
<div id='output'></div>

JAVASCRIPT

$(document).ready(function(){
    $('#anonFunction').on('keyup', function () {
        return _.debounce(debounceIt, 500, false); //Why does this differ from #function
    });
    $('#noReturnAnonFunction').on('keyup', function () {
        _.debounce(debounceIt, 500, false); //Not being executed
    });
    $('#exeDebouncedFunc').on('keyup', function () {
        _.debounce(debounceIt, 500, false)(); //Executing the debounced function results in wrong behaviour
    });
    $('#function').on('keyup', _.debounce(debounceIt, 500, false)); //This is working.
});

function debounceIt(){
    $('#output').append('debounced');
}

anonFunction and noReturnAnonFunction does not fire the debounce function; but the last function does fire. I do not understand why this is. Can anybody please help me understand this?

EDIT Ok, so the reason that the debounce does not happen in #exeDebouncedFunc (the one you refer) is because the function is executed in the scope of the anonymous function and another keyup event will create a new function in another anonymous scope; thus firing the debounced function as many times as you type something (instead of firing once which would be the expected behaviour; see beviour of #function)?

Can you please explain the difference between #anonFunction and the #function. Is this again a matter of scoping why one of them works and the other does not?

EDIT Ok, so now I understand why this is happening. And here is why I needed to wrap it inside an anonymous function:

Fiddle: http://jsfiddle.net/6hg95/5/

HTML

<input id='anonFunction'/>
<div id='output'></div>

JAVASCRIPT

(function(){
    var debounce = _.debounce(fireServerEvent, 500, false);

    $('#anonFunction').on('keyup', function () {
        //clear textfield
        $('#output').append('clearNotifications<br/>');
        debounce();
    });

    function fireServerEvent(){
        $('#output').append('serverEvent<br/>');
    }
})();

As Palpatim explained, the reason lies in the fact that _.debouce(...) returns a function, which when invoked does it's magic.

Therefore in your #anonFunction example, you have a key listener, which when invoked does nothing but return a function to the invoker, which does nothing with the return values from the event listener.

This is a snippet of the _.debounce(...) definition:

_.debounce
function (func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      if (immediate && !timeout) func.apply(context, args);
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  } 

Your key event listener must invoke the returned function from _.debounce(...), or you can do as in your non-anonymous example and use the returned function from the _.debounce(...) call as your event listener.

Lodash debounce not working when placed inside a method, I am trying to implement a debounce on an input field using the lodash debounce function. It works fine if I addd the loadash debounce directly� Lodash debounce not working. Is there an issue with using Loash debounce with anonymous function? lodash's debounce function is a higher order function and

debounce doesn't execute the function, it returns a function with the debounciness built into it.

Returns

(Function): Returns the new debounced function.

So your #function handler is actually doing the Right Thing, by returning a function to be used by jQuery as a keyup handler. To fix your #noReturnAnonFunction example, you could simply execute the debounced function in the context of your function:

$('#noReturnAnonFunction').on('keyup', function () {
    _.debounce(debounceIt, 500, false)(); // Immediately executes
});

But that's introducing a needless anonymous function wrapper around your debounce.

passing .bind argument through debounce throwing type error , https://github.com/lodash/lodash/blob/3.0.9-npm-packages/lodash.isfunction/ index.js. I'm not very saavy on this but bound functions have no� the lodash debounce function not executing the input function. <Slider value={this.state.slider} onValueChange={(slider) => { _.debounce(() =>; { console.log(this

Think easier

_.debounce returns a debounced function! So instead of thinking in terms of

$el.on('keyup'), function(){
   _.debounce(doYourThing,500); //uh I want to debounce this
}

you rather call the debounced function instead

var doYourThingDebounced = _.debounce(doYourThing, 500); //YES, this will always be debounced

$el.on('keyup', doYourThingDebounced);

Debouncing and Throttling Explained Through Examples, Having a debounced or throttled version of our function is especially useful when we John Resig published a blog post about the problem where it was explained how bad In underscore.js, the option is called immediate instead of leading. As you mention, it's less work for you, and it means we can choose lodash/underscore, debounce/throttle. In my case I was already using lodash/debounce, so it's better for me if it's not duplicated. I guess that's a likely scenario now that Vue doesn't include a debouncer. If there's overwhelming public outcry, you can always reconsider!

You can return the debounce function like this:

(function(){
    var debounce = _.debounce(fireServerEvent, 500, false);

    $('#anonFunction').on('keyup', function () {
        //clear textfield
        $('#output').append('clearNotifications<br/>');
        return debounce();
    });

    function fireServerEvent(){
        $('#output').append('serverEvent<br/>');
    }
})();

javascript lodash debounce not working in anonymous function , javascript lodash debounce not working in anonymous function? _.debounce function (func, wait, immediate) { var timeout; return function() { var context = this, � Many lodash methods are guarded to work as iteratees for methods like _.reduce, _.reduceRight, and _.transform. (Function): The function to debounce.

More generally, if you want a debounce with a trailing behaviour (accounts for last click, or more likely last change on a select input), and a visual feedback on first click/change, you are faced with the same issue.

This does not work:

$(document).on('change', "#select", function() {
    $('.ajax-loader').show();
    _.debounce(processSelectChange, 1000);
});

This would be a solution:

$(document).on('change', "#select", function() {
    $('.ajax-loader').show();
});
$(document).on('change', "#select", _.debounce(processSelectChange, 1000));

Debouncing and Throttling in JavaScript, The anonymous function is called each time the user types in the Debouncing and throttling are not something provided by JavaScript itself. Dismiss Join GitHub today. GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.

Debouncing your JavaScript events, Debouncing is a way of forcing a function to wait a certain period of time scroll and resize can cause huge performance issues on certain browsers. An anonymous callback function var logDebounce = debounce(function� @jdalton thanks for lodash (et. al.) seems like it might be a moderately common use-case. ideally I want to make a function which is capable of debouncing based on arguments' uniqueness. here is my first attempt, but it is not working how I'd expect

lodash debounce not working in anonymous function, Hello I cannot seem to figure out why the debounce function works as expected when passed directly to a keyup event; but it does not work if I wrap it inside an� To ensure that a JavaScript function is not called more than once every few seconds, you can run wrap it it in the “debounce” function available in lodash: const run = => console.log('abc'); const lag = _.debounce(run, 1500); lag(); lag(); lag(); The output will be: abc. In this case, the function will only get run once.

How to Use Debounce and Throttle in JavaScript | by Moon, After a while, I learned a workaround for this problem: throttle or debounce. If you know how JavaScript's asynchronous functions and HOF work under the hood, you could This anonymous function is a HOF that returns another function. I had to go into the logic details when I needed to create a simular custom debounce for vue-instantsearch. Your code have no concept of immediate (look at underscore debounce function arguments and condition for this) which basically makes it fire a request right after first character is pressed and not wait for the timeout.

Comments
  • +1 for this explanation. Basically this: $('#function').on('keyup', _.debounce(debounceIt, 500, false)); //This is working. is WHY debounce returns a function. It's beautiful like this, and Just Makes Sense™
  • So many upvotes, but imho this can not work. On every keyup the function debounceIt will be converted into a debounced function AND executed immediately, with the effect that debounceIt will be delayed for 500ms. This will be repeated for every keypress! So in the end, your code is equivalent to $('#noReturnAnonFunction').on('keyup', function (){setTimeout(debounceIt, 500);}) No debouncing... only delaying.
  • What if I have to call multiple functions on keyup and only one of them should be debounced?
  • It seems this is not needed in this situation. Similar idea helped me in another situation though.
  • _.debounce does not return the function, but the time it is set to timeout for.
  • According to documentation _.debounce does return the function. ref. lodash.com/docs/#debounce