Home >Web Front-end >JS Tutorial >Implementing function debounce in angular.js and vue.js
In the search input box, only after the user stops typing, subsequent operations, such as initiating an HTTP request, etc. will be performed.
Students who have studied electronic circuits should know about button anti-shake. The principle is the same: that is, when the action is called n milliseconds, the action will be executed. If the action is called again within these n milliseconds, the execution time will be recalculated. This article will discuss how to achieve anti-shake of user input in angular.js and vue.js respectively. (If you want to learn more, go to the PHP Chinese website AngularJS Development Manual to learn)
Write the debounce function as a service, which is more convenient Call at:
.factory('debounce', ['$timeout','$q', function($timeout, $q) { // The service is actually this function, which we call with the func // that should be debounced and how long to wait in between calls return function debounce(func, wait, immediate) { var timeout; // Create a deferred object that will be resolved when we need to // actually call the func var deferred = $q.defer(); return function() { var context = this, args = arguments; var later = function() { timeout = null; if(!immediate) { deferred.resolve(func.apply(context, args)); deferred = $q.defer(); } }; var callNow = immediate && !timeout; if ( timeout ) { $timeout.cancel(timeout); } timeout = $timeout(later, wait); if (callNow) { deferred.resolve(func.apply(context,args)); deferred = $q.defer(); } return deferred.promise; }; }; }])
Call the method, inject debounce into the controller/directive that needs to use this function, and also inject $watch, and then:
$scope.$watch('searchText',debounce(function (newV, oldV) { console.log(newV, oldV); if (newV !== oldV) { $scope.getDatas(newV); } }, 350));
You're done!
First register debounce in the public function file
export function debounce(func, delay) { let timer return function (...args) { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { func.apply(this, args) }, delay) } }
Then introduce debounce in the component that needs to be used, and within the created life cycle Call:
created() { this.$watch('searchText', debounce((newSearchText) => { this.getDatas(newSearchText) }, 200)) }
You’re done!
Quote
1. https://stackoverflow.com/questions/29771011/angularjs-watch-with-debounce 2. https://www.cnblogs.com/fsjohnhuang/p/4147810.html
Okay, this article is over (if you want to see more, go to the PHP Chinese website AngularJS User Manual to learn), there are questions You can leave a message below to ask questions.
The above is the detailed content of Implementing function debounce in angular.js and vue.js. For more information, please follow other related articles on the PHP Chinese website!