Home > Back-end >  How debounce function return the function in Javascript
How debounce function return the function in Javascript

Time:12-03

I have this debounce function:

const selectElement = document.querySelector('input');

const debounce = (cb, time = 1000) => {
  let timer;

  return (...args) => {
    console.log('run inner function')
    if (timer) {
      clearInterval(timer)
    }
    timer = setTimeout(() => cb(...args), time)
  }
}

const onChange = debounce((e) => {
  console.log('event', e.target.value)
})
selectElement.addEventListener('input', onChange);
<input input={onChange}/>

The code works ok, but I want to understand, how the returned function is triggered inside debounce function, because I know that if a function returns another function I need to call it like this: debounce()() to trigger the second one, but in our case we trigger the function only once debounce() in addEventListener, but how the second call happens?

CodePudding user response:

You only would call it like debounce()() if you want to immediately call the function it returns (and throw away the entire point, since with that method you could only call it once).

It returns a function, which here you've named onChange. onChange is called when the selectElement has a input event. You don't say selectElement.addEventListener(('input', onChange()) (emphasis on onChange()) because that would just call onChange once (immediately, not even on the first input event) and attempt to run a function returned from onChange, but it doesn't

CodePudding user response:

Maybe it would help to first acknowledge that:

debounce()();

can be rewritten as

let onChange = debounce();
onChange();

And you've passed onChange to addEventListener here:

selectElement.addEventListener('input', onChange);

The internals of the event listener mechanism will remember the onChange you passed in and will call onChange() when the input event occurs.

Imagine an implementation of function addEventListener(type, listener) {} that arranges for listener() to happen when the event occurs.

This is done to defer the function call. The first part (debounce()) creates a function immediately (synchronously). But the call to the function that debounce() returned is deferred until the event occurs.

  • Related