Search code examples
javascripttypescriptobservablehandsontable

Ignore multiple successive function calls in Typescript from within the function?


I am trying to implement autocomplete using Handontable (Angular) by fetching data from the server as the user types.

I notice the API calls are made every time the user input changes but I would like to limit the number of API calls by waiting 1 second for the user to stop typing before making the call.

I have done this in the past when I controlled the event by using debounceTime but not sure how to implement that here.

    ...
    column.source = function(query, callback) {
      $component.dataService.getValidValues().subscribe(
        arg => {
          callback(arg);
        },
        err => {
          ...
        }
      );
    }
    ...

Adding debounceTime(1000) here doesn't prevent multiple calls from happening.

$component.dataService.getValidValues().debounceTime(1000).subscribe(...)


Solution

  • As already explained by others you need to debounce the input. In your case this would be the invocation of the function.

    One way to achieve that is using a subject that you create somewhere in your code:

    const sourceRequest = new Subject();
    sourceRequest.debounceTime(1000).subscribe(callback => {...});
    

    The code you currently have inside function(query, callback) { goes into subscribe. The column definition is then changed to this:

    column.source = function(query, callback) {
      sourceRequest.next(callback);
    }