0

I'm using Angular, Javascript and Typescript and Ionic. I have a function createDropdown(inputField, arrayOfItems) which will attach a dropdown to the input field being passed populating the dropdown with the array provided.

This will work as a "autocomplete" dropdown, that's why I need a add an event listener "input" so it will look something like this:

createDropdown(inputField, arrayOfItems){
  inputField.addEventListener("input",()=>{
  //Logic to create dropdown
  });
}

The problem is that, after adding the event listener to the input field, if the user spams a key "A" for instance from the keyboard, then this creates lag or delay and eventually the app crashes. Is there a way to prevent this from happening? I have tried "keyup", and it fixes it. However, with this, pressing any key from the keyboard will trigger the createDropdown function, for example: pressing "Control" or "Alt".

The end result should be, having the user typing in an input field, then the results that match should be displayed in the dropdown so the user can select from it. The more they type, the more accurate the results become.

relze
  • 3
  • 2
  • I'm assuming the key listener is triggering an API call or something? If you're using rxjs, there's the [`debounce`](https://rxjs.dev/api/operators/debounce) operator to reject events that are too close to each other. Put that in the pipeline that receives events and leads to an API call. – Carcigenicate Jan 30 '22 at 19:20
  • The key listener is only getting/filtering data that is already stored in memory and populating the dropdown with that data. I'm trying to return a promise inside the event listener. I'm using a promise instead of an observable, because then subscribing and unsubscribing can be messy. For debounce, I need to use .debounce(time).subscribe() right? – relze Jan 30 '22 at 20:03
  • Ya, something like have the event listener emit to a `EventEmitter` or something similar, then do `emitter.pipe(debounce(time)).subscribe()`. At least that's how I've seen a similar problem solved previously. – Carcigenicate Jan 30 '22 at 20:27

2 Answers2

0

You could use for example setTimeout() + implementation of a spinner.

Here an example for what I mean

https://stackblitz.com/edit/how-to-trigger-an-event-in-input-text-after-i-stop-typingwritin

DeanTwit
  • 325
  • 4
  • 8
  • This prevents the user from spamming a key on the UI but, what I meant to say is that the user should be able to do that, I just don't want that particular key to be calling my createDropdown() function multiple times since that causes problems. – relze Jan 30 '22 at 21:56
  • I ended up using setTimeout(()=>) with a timer that resets every time the user press down a key, adding a delay of few ms – relze Feb 01 '22 at 01:01
0

What you're looking for is called "debouncing input". Take a look here: https://stackoverflow.com/a/36849347/4088472

Slava Knyazev
  • 5,377
  • 1
  • 22
  • 43