Home > Blockchain >  Why is the return function in my debounce function never called? Angularjs
Why is the return function in my debounce function never called? Angularjs

Time:04-19

I am learning about debouncing, and the concept makes sense, but I don't know why the arrow function that my debounce function returns is never run.

    public debounce = (func, delay, event) => {
    console.log(func, delay, event.target.value);
    let debounceTimer;
    return (...args) => {
      clearTimeout(debounceTimer);
      console.log(func, delay, event.target.value);
      debounceTimer = setTimeout(() => func.apply(this, [event.target.value]), delay);
    };
  };
  public resolveInput(event) {
    console.log('resolved', event);
  }

And this is how I call the debouncer:

<input (input)="debounce(resolveInput, 1000, $event)" />

Any explanation would be helpful. I understand that we need to return a function so that the setTimeout exists in its own scope so that we can reset it whenever we receive a new input before the time has run out, but I don't know why that return function isn't being invoked. Thank you all again!

CodePudding user response:

I think you don't need arrow function here.

You can write directly this:

public debounceTimer;

public debounce = (func, delay, event) => {
  console.log(func, delay, event.target.value);
  clearTimeout(this.debounceTimer);
  console.log(func, delay, event.target.value);
  this.debounceTimer = setTimeout(() => func.apply(this, [event.target.value]), delay);

};

public resolveInput(event) {
  console.log('resolved', event);
}
  • Related