Debounce function with args underscore

Javascriptunderscore.js

Javascript Problem Overview


I've got a function which takes in some arguments. But usage of underscore debounce is :

var lazyLayout = _.debounce(calculateLayout, 300);

But in my case calculateLayout needs some arguments to run. How can I pass them in this case?

Update :

Sample calculateLayout function :

var calculateLayout = function(a,b) {
  console.log('a is ' + a + ' and b is ' + b);
}

Javascript Solutions


Solution 1 - Javascript

You don't need an anonymous function in the middle, arguments will automatically be passed to the original function when you run the debounced version.

  var debounceCalculate = _.debounce(calculateLayout, 300);
  debounceCalculate(a,b);

As an advantage you don't have to hardcode-bind the arguments in advance

You can try it and if curious just check the source

Solution 2 - Javascript

You should be able to just use an anonymous function as the first argument, then call whatever you like in it:

_.debounce(function(){
    calculateLayout(20, 30);
}, 300);

Solution 3 - Javascript

@Jamie's answer is better.

I'll keep my original answer as below, although the it should be better to use Jamie's answer if you are familiar with JS:

var calculateLayout = function(a,b) {
  console.log('a is ' + a + ' and b is ' + b);
}

var debounceCalculate = _.debounce(function(a, b){
    calculateLayout(a, b);
}, 300);

debounceCalculate(1, 2);

Solution 4 - Javascript

Since nobody has written the one liner without extra var and function, I'll do it myself:

_.debounce(calculateLayout, 300)(a, b);

Debounce function returns another function, so you can call it just afterwards debounce is executed.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGandalf StormCrowView Question on Stackoverflow
Solution 1 - JavascriptJaime AgudoView Answer on Stackoverflow
Solution 2 - JavascriptmgherkinsView Answer on Stackoverflow
Solution 3 - Javascripthuan fengView Answer on Stackoverflow
Solution 4 - JavascriptMax ZavernutiyView Answer on Stackoverflow