Debounce, vue. jsdebounce
Problem description
In the search input box, subsequent operations, such as initiating an Http request, are performed only after the user stops entering the input.
Those who have learned electronic circuits should be aware of the anti-shake button. The principle is the same: that is, this action is executed only after n milliseconds of the Call action. If this action is called again within n milliseconds, the execution time is recalculated. This article will discuss how angular. js and vue. js achieve anti-shake effects on user input.
Angular. js Solution
Write the deshake function as a service to facilitate multiple calls:
.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 by injecting debounce into the controller/directive that needs to use this function, or injecting $ watch, and then:
$scope.$watch('searchText',debounce(function (newV, oldV) { console.log(newV, oldV); if (newV !== oldV) { $scope.getDatas(newV); }}, 350));
Success!
Solutions in Vue. js
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) }}
Debounce is introduced into the required components and called within the created lifecycle:
created() { this.$watch('searchText', debounce((newSearchText) => { this.getDatas(newSearchText) }, 200))}
Success!
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.