0

In this post we have a snippet of debouncing function: Can someone explain the "debounce" function in Javascript

It uses recursion as the algorithm. However, this doesn't seem to fit the typical recursion situation, where each step has a somewhat smaller instance of the previous step. I was wondering if there are any advantage using recursion at all? To me, this method would inevitably burden call stacks by recursive calls. Could someone list some reasons backing up this recursive approach? Thanks.

Community
  • 1
  • 1
Jinghui Niu
  • 990
  • 11
  • 28

1 Answers1

0

There is no recursion there.

I think that you are mistaking the inner keyword function as a call to the function being defined.

That is not the case

This is a function that returns a (different) function.

When you call debounce(foo) you get back a function.

e.g.

function foo (foothing) {
  console.log(foothing)
}

debounced_foo = debounce(foo)

Then you can call that function:

debounced_foo(my_param)
debounced_foo(my_param)
debounced_foo(my_param)

And it will do what foo() would have done, except it will only do it once rather than many times in quick succession.

GreenAsJade
  • 14,459
  • 11
  • 63
  • 98