0

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.

3
  • $scope.updateTextLogo= function() { if ($scope.logoText.text >= 4) executeSomething() }; Commented Mar 14, 2019 at 14:00
  • Hey, I have just given above test as an example. The user is not restricted to the number of letters. I just want to call the function after a few delays. Like if a user only enters H and then wait for 2 seconds, the function will be called. Commented Mar 14, 2019 at 14:08
  • Hey, I found this plunkr. plnkr.co/edit/HfPDC4veoW9KlVrC7Tly?p=preview. Commented Mar 14, 2019 at 14:21

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, mine is 1.2.7. How to do in version less than 1.3?
2

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...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.