Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay code using debounce in angularjs

Tags:

angularjs

I have to write email verification function in angularjs. I want to make a post request after 2 second when user has done editing with email id. Is there any pre defined method in angularjs for this. fiddle

var app = angular.module('form-example', []);
    app.controller('formctrl',function($scope){
        var ctrl= this;
        ctrl.verifyEmail= function(){    
        console.log('hiiii')
        }

    })
like image 374
Jitender Avatar asked Sep 15 '15 14:09

Jitender


People also ask

What is debounce in AngularJS?

debounce : integer value which contains the debounce model update value in milliseconds. A value of 0 triggers an immediate update. If an object is supplied instead, you can specify a custom value for each event. For example: ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"

What is $timeout in AngularJS?

The '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.

What is input debounce?

What is debounce? Debounce delays the processing of a function bound to a certain user input event until a certain amount of time has passed. In other words the function is only executed once per specific user input event, even it the event is triggered multiple times.

What is debounce?

Debouncing is a programming pattern or a technique to restrict the calling of a time-consuming function frequently, by delaying the execution of the function until a specified time to avoid unnecessary CPU cycles, and API calls and improve performance.


1 Answers

You can use ng-model-options to delay the model update. Here is an working example. This feature was added in Angular 1.4+.

var app = angular.module("myApp", []); 
app.controller("myCtrl", function($scope) {
    
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<script>

</script>

<div ng-app="myApp" ng-controller="myCtrl">
  <input ng-model="email" ng-model-options="{ debounce: 2000 }"/>
  <br/><br/>
  The email will be updated here after 2 seconds: <strong>{{email}}</strong>
</div>

</body>
</html>
like image 169
Hari Das Avatar answered Oct 15 '22 01:10

Hari Das