0

I am trying to implement debouncing in angular, I know it provides a debounceTime rxjs operator, but I want to implement it from scratch. So when I use below debounce function.

debounce(func: Function, limit = 500) {
    let timer: any;
    return function () {
      let context = this;
      clearTimeout(timer);
      timer = setTimeout(() => {
        func.apply(context, arguments);
      }, limit);
    }
  }

I have a Search Function which uses a injected service(ExerciseService) to make an api call

search(query: string) {
    this.exerciseService.searchExercises(query).subscribe(exercises => {
      this.exercises = exercises;
    });
}

I am calling the search method like this

optimizedSearch = this.debounce(search, 500);

The optimizedSearch method is binded to a click event in the template like this

<div class="search">
    <input type="text" placeholder="Search..." (keyup)="optimizedSearch($any($event).target.value)()">
    <button (click)="optimizedSearch($any($event).target.value)()">Search</button>
</div>

So now what's happening is that the value of 'this' keyword in the search method is being 'undefined'. Seems that there might be some context issue.

Can someone help me fix this? Thanks in advance

My component looks like this

import { Component, OnInit } from '@angular/core';
import { ExercisesService } from '../exercises.service';

@Component({
  selector: 'app-exercises',
  templateUrl: './exercises.component.html',
  styleUrls: ['./exercises.component.css']
})

export class ExercisesComponent implements OnInit {
  
  constructor(private exerciseService: ExercisesService) { }

  ngOnInit(): void {
    
  }






search(query: string) {
    this.exerciseService.searchExercises(query).subscribe(exercises => {
      this.exercises = exercises;
    });
}




debounce(func: Function, limit = 500) {
    let timer: any;
    return function () {
      let context = this;
      clearTimeout(timer);
      timer = setTimeout(() => {
        func.apply(context, arguments);
      }, limit);
    }
  }



optimizedSearch = this.debounce(search, 500);

}
  • “The optimizedSearch method is binded to a click event in the template like this[:] `optimizedSearch($event.target.value)`” — actually, this one line is not nearly sufficient detail to diagnose the issue. – user3840170 Apr 09 '23 at 17:55
  • I added my component class. Will that help?? – Manav Saini Apr 10 '23 at 08:42
  • `optimizedSearch = this.debounce(search, 500)` doesn't even work, did you write `optimizedSearch = this.debounce(this.search, 500)`? As @JSONDerulo hinted at, you need to use `optimizedSearch = this.debounce(this.search.bind(this), 500)` – Bergi Apr 10 '23 at 11:05

0 Answers0