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.