Writing a debouncer service with Angular.js
Let's say that you would like to have an input field where each time the user changes the input, your app updates the url, and fetches the search results from the server.
The best user experience will be provided if you let the user finish typing, and show the results straight afterwards.
To do that, you can create a simple debouncer service, that will execute a function of your choice, after a certain time that the user hasn't typed anything.
$scope.$watch('searchInput', function(newVal, oldVal){ if (newVal===oldVal) return; debouncer('search', function(){doSearch(newVal);},500); });
Using the code above, you can call your search time everytime searchInput changes, but only 500ms after the user stopped typing, to provide a smoother, better user experience.
And here's my code for the debouncer service:
myApp.factory('debouncer', function($timeout){ var timeout = {}; return function(debouncer, cb, timeoutMs){ if (timeout[debouncer]){ $timeout.cancel(timeout[debouncer]); } timeout[debouncer] = $timeout(cb, timeoutMs); }; });
You can see a working example on: jsfiddle.net/itamarwe/cFECf/












