0

I am developing a web application using AngularJS (i.e. Angular 1). Although the title may seem trivial, I find myself facing a rather complicated problem (I think). The problem is this: I have a text input box (in a form) associated with an asynchronous service making an HTTP call (I don't think it's important that I show the code here). When the user types at least two characters the service should start only after 2000 milliseconds.

Unfortunately I was asked that if during this waiting time (2000 ms) the user still writes some other characters, the previous call (the one associated, for example, to the two characters) will no longer have to be made. In practice, during the 2000 ms the user must not have written anything more in the input text, otherwise it would have to be counted again 2000ms associated with the most recent string to make the call. If there was another countdown in progress, it simply goes discarded and the call for that (oldest) string will simply be ignored.

I can't do this in my JavaScript code. I put here the method associated with the input text:

ctrl.onSearch = function(text){
        
    if (text.length >= ctrl.minLenght) { 

        $timeout(function () {
            
            // code making the call 
            
        }, 2000);

    }
}

text is the dynamic variable always associated with the text string inserted in this input field. ctrl.minLenght is setted to 2 and is used to not start any calls if the string entered has less than two characters.

wishyouwerehere
  • 163
  • 1
  • 3
  • 8
  • 1
    You should check how debouncing works in JS. That will help you. There are plenty of code samples you can find on google. This is more like an open question.. like you have a problem but dont know how to solve it.. Just google it and you will find an answer IMO. – Sagar Agrawal Jan 26 '21 at 10:16
  • This might be helpful: [Delay code using debounce in angularjs](https://stackoverflow.com/questions/32589154/delay-code-using-debounce-in-angularjs) – Ivar Jan 26 '21 at 10:17
  • This is called "debouncing" (whether in JavaScript or otherwise). (The term comes from electronics, where it was necessary to handle the electric "bounce" that occurs as a pair of contacts (as in a key) come into close proximity prior to fully connecting.) Basically, start a timer for 2sec later and cancel that timer when the next key comes in before those 2sec are up. – T.J. Crowder Jan 26 '21 at 10:18

0 Answers0