Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How debounce function return the function in Javascript

Tags:

javascript

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) {
      clearTimeout(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?

like image 960
Asking Avatar asked Nov 16 '25 15:11

Asking


1 Answers

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.

like image 61
Wyck Avatar answered Nov 18 '25 04:11

Wyck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!