When you want to use $scope.$watch to monitor changes to a variable in AngularJS you may not want to execute the watch on every scope change, so you need to use debounce. A debounce function limits the rate at which a function can fire.

You can use Underscore.js but you may not want to include the underscore library in your app in which case below is a angular version of debounce.

All you do is wrap the $watch listener in the debounce. The usage for $scope.$watch is:

In the below example you want to watch the products array for changes and increment a counter with a debounce of 1 second. The products data is displayed in a form using ng-repeat.

 

Tristan Claridge on EmailTristan Claridge on LinkedinTristan Claridge on Twitter
Tristan Claridge
Web Developer at Claridge Media
Tristan is a full stack developer with over 10 years experience developing innovative projects using LAMP, jQuery, AngularJS, NodeJS, and others. He has started and operated a variety of businesses including building the software systems used by, or sold by, the businesses. Tristan grew up in Brisbane, Australia, and has a couple of degrees from the University of Queensland. Tristan now lives in Dunedin, New Zealand, enjoying world-class internet speeds and the beautiful country.