JS: What are the args in a debounce function

Tags:



I am trying to grasp a debounce function in an existing codebase I am working on but I have a question that I can’t understand while looking at it. What is (...args) in this scenario? I know it’s a rest parameter but where did it come from and what is the purpose of args here? Why can’t that just be empty and then called like fn() in the setTimout?

const debounce = (fn, delay) => {
    let id;
    return function(...args) {
        if (id) {
           clearTimeout(id)
        }
        id = setTimeout(() => {
           fn(...args);
        }, delay);
    }
}

Answer

The function being returned from debounce() is supposed to act exactly the same as the function being provided, except for the fact that we’re limiting how often it gets called. This means that if the original function was supposed to take two parameters, the returned function should too. That’s why spread is being used.

As a simpler example, lets consider a wrapper function that just adds 1 to whatever gets returned.

function alsoAdd1(fn) {
  return function(...args) {
    return fn(...args) + 1
  }
}

To use it, we can do the following:

> multiplyAndAdd1 = alsoAdd1(function(x, y) { return x * y })
> multiplyAndAdd1(2, 3)
7
> doubleAndAdd1 = alsoAdd1(function(x) { return x * 2 })
> doubleAndAdd1(2)
5

Notice how it doesn’t matter how many parameters we pass into the wrapped function (like doubleAndAdd1), they’re all get passed along to the original function (the double function). This is because we’re using the spread operator.

If we look at the definition of alsoAdd1, we see that it’ll give back a function that takes an arbitrary number of arguments, and passes all the arguments it receives into the function its wrapping.

The debounce() function is doing exactly the same thing, there’s just a little bit more going on. These wrapper functions can be a little tricky to wrap your head around, so try going through those above examples slowly and see if you can grasp what they’re doing.



Source: stackoverflow