Consider exploring Reactive Extensions for JavaScript as a potential solution. One approach is to set up the keyup event as a source of events and then apply throttling to handle the events efficiently. You can find a relevant example in the README that aligns with your requirements...
var $input = $('#input'),
$results = $('#results');
/* Capture the value from each key up event */
var keyups = Rx.Observable.fromEvent(input, 'keyup')
.map(function (e) {
return e.target.value;
})
.filter(function (text) {
return text.length > 2;
});
/* Throttle/debounce the input for 500ms */
var throttled = keyups
.throttle(500 /* ms */);
/* Ensure only distinct values are processed, filtering out control characters */
var distinct = throttled
.distinctUntilChanged();
If you prefer not to use the filter
condition based on length > 2
, simply omit that part. Afterward, add a subscribe
function at the end to handle your specific event processing needs
distinct.subscribe(function(value) {
scope.$apply(function () {
ngModel.$setViewValue(value);
});
});
Additionally, there are specific bindings available for AngularJS that you may find beneficial.