Anuj TBE
Anuj TBE

Reputation: 9790

add delay to ng-keyup in angularjs

In my AngularJS application, I have a binding to the input field on ng-keyup to call a function every time value of the input field is changed.

<input type="text" ng-model="logoText.text" ng-keyup="updateTextLogo();">

This function updates text on a canvas and performs few more actions which take 2-3 seconds.

While type each letter with little delay (slow) is working fine by fast typing results in overlaying of canvas data.

Is it possible to add delay to execute the function on keyup?

Ex., Current scenario is that if a user has to type Hello the function is called on each letter.

I want to add a delay so that if the user has entered Hell within the dealy, the Hell word will be processed together instead of each letter.

Upvotes: 0

Views: 1132

Answers (2)

vcode
vcode

Reputation: 453

If you are using angular 1.3 or above, you have debounce in ng-model-options.

<input type="text" ng-model="logoText.text" ng-model-options="{debounce: 1000}" ng-keyup="triggerTimer();">

Debounce affects the assigning of value to the scope variable.

Upvotes: 3

Stefan Meier
Stefan Meier

Reputation: 153

You can use the $timeout service:

<input type="text" ng-model="logoText.text" ng-keyup="triggerTimer();">

var timerStarted = false;
$scope.triggerTimer = function() {
  if(!timerStarted) {
    $timeout(updateTextLogo, 2000);
    timerStarted = true;
  }
}

The function updateTextLogo should reset the timerStarted flag, so that the timer can be started again, when there come further characters.

var updateTextLogo = function() {
  timerStarted = false;
  // do stuff...
}

Upvotes: 2

Related Questions