Home > Back-end >  Angular- Adding event listener "input" and prevent user from spamming a key
Angular- Adding event listener "input" and prevent user from spamming a key

Time:01-31

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.

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related