Search code examples
angulartypescriptdebouncing

How to debounce a method in Angular


I have a method call foo() who is making an API call, and the foo() method is calling inside a slider eventChange method, the slider has a step of 100 while the maxNum is 500k+ so when someone slide the slider it will call the eventChange method more than 1 time.

Now I want to debounce the method foo() for 400ms before making the API call like we do on FormControl value changes.

I've tried something with lodash debounce

var debounce = _.debounce(function(){

  foo();

}, 30000);

debounce();

but it's saying that foo() is not a function. How can I debounce the method foo() with raw TypeScript.

NOTE. Foo() is not bind able to any html.


Solution

  • Okay, somehow I manage to solve the issue through setTimeout and it's working perfect for me as a debouncer,

    onSliderEventChanges(event:ChangeContext){ 
    
      if(this.timerid !== null){
        clearTimeout(this.timerid);
      }
      this.timerid  = setTimeout(() => 
      {
        this.foo(false);
        this.timerid = null;
      }, 400);
    
    } 
    

    The first if will always clear the last running timeOut, so end of the sliding I will have only one call to the foo() as only the last timeOut is alive.

    setTimeout always return atimerId.