Explain Codes LogoExplain Codes Logo

Angularjs: Clear $watch

javascript
angularjs
watch
best-practices
Anton ShumikhinbyAnton Shumikhin·Jan 29, 2025
TLDR

To immediately cancel a $watch, invoke the function it returns upon creation:

var unwatch = $scope.$watch('property', (newVal, oldVal) => { // Reaction to changes... or probably I'm just overreacting }); // To stop watching... unwatch(); // Guess it was just a phase

Invoke unwatch() to halt the $watch, ceasing all further reactions to property changes and optimizing resources.

Different scenarios, various solutions

When conditions demand a farewell

A $watch may need to leave upon meeting certain criteria. In such cases, call within the callback function:

var unwatch = $scope.$watch('property', function(newValue) { if (newValue === "Enough!") { unwatch(); // Stop nagging, you got your answer! } });

Juggling with multiple strict observers? No problem!

Has too many $watches taken a toll on your peace? Track and remove them in a jiffy:

let watches = []; watches.push($scope.$watch('property1', callback1, true)); watches.push($scope.$watch('property2', callback2, true)); // Time to let go of those nosy neighbors watches.forEach(unwatch => unwatch()); watches = []; // Starting afresh!

The casual stalker: Time-bound watch

A $watch can also be time-bounded, and made to leave after a specified duration using setTimeout or AngularJS’s $timeout:

var unwatch = $scope.$watch('property', callback); $timeout(function() { unwatch(); // Guess the charm was short-lived }, 3000);

Best practices: Getting rid of that nagging $watch

The one-time wonder

Certain $watch expressions may only be required once:

$scope.$watch('oneTimeProperty', function (newValue, oldValue) { if (newValue === oldValue) return; // Because change is the only constant // The task that requires absolute attention... for a while doSomething(newValue); unwatch(); // Isn't it liberating to let go? });

Give your app a performance boost

To avoid any potential memory leaks and optimum application speed, make sure to clear unnecessary $watches at regular intervals.