简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM