What You’ll Learn
What is debouncing in AngularJS?
Why is debouncing important for user input?
Using ng-model-options
to debounce input events
Practical examples with real-world use cases
1️⃣ What is Debouncing?
Debouncing is a technique that delays the execution of a function until after a certain period of inactivity.
In AngularJS, when a user types in an input field, ng-model
updates the model instantly. This can lead to:
- Too many API calls (wasted network requests)
- Unnecessary re-renders (slower performance)
- Laggy UI updates (bad user experience)
Example Without Debouncing
<input type="text" ng-model="searchText" ng-change="fetchResults()" />
🔹 Issue: fetchResults()
runs every time the user types a letter!
🔹 Solution: Debounce input to wait before executing the function.
2️⃣ Using ng-model-options
for Debouncing
AngularJS provides ng-model-options
to control how ng-model
updates.
Syntax:
ng-model-options="{ debounce: time_in_ms }"
This ensures the model updates only after the user stops typing for a specified delay.
3️⃣ Implementing Debouncing in Search Input
Step 1: Debouncing API Calls
<input type="text" ng-model="searchText"
ng-model-options="{ debounce: 500 }"
ng-change="fetchResults()"
placeholder="Search..." />
app.controller('SearchController', function ($scope) {
$scope.fetchResults = function () {
console.log('Fetching results for:', $scope.searchText);
};
});
Now, fetchResults()
is called only after 500ms of user inactivity!
4️⃣ Setting Different Debounce Values for Blur and Keypress
You can set separate debounce times for keypress and blur events.
Example: Faster Update on Blur, Slower on Typing
<input type="text" ng-model="userInput"
ng-model-options="{ debounce: { 'default': 500, 'blur': 0 } }"
placeholder="Type something..." />
🔹 Typing: Updates after 500ms
🔹 Blur (losing focus): Updates immediately
5️⃣ Debouncing Input in Forms
Example: Debounced Form Validation
<form name="userForm">
<input type="email" name="email" ng-model="user.email"
ng-model-options="{ debounce: 300 }"
required placeholder="Enter Email" />
<span ng-show="userForm.email.$error.required">Email is required</span>
</form>
Now, validation messages appear only after 300ms of user inactivity.
6️⃣ Practical Use Cases for Debouncing
✔ Search Inputs: Prevents unnecessary API calls while typing
✔ Live Form Validation: Avoids showing errors while the user is still typing
✔ Auto-save Feature: Triggers save only after a user stops typing
✔ Filtering Data: Improves performance when filtering large datasets