Jason Tree Jason Tree - 3 months ago 25
AngularJS Question

How do you reset a “$timeout”, and disable a “$watch()”?

How do you reset a “$timeout”, and disable a “$watch()”?

var customTimeout = $timeout(function () {
// arbitrary code
}, 55);

Answer

The key to both is assigning the result of the function to a variable.

To cleanup the timeout, just “.cancel()” it:

$timeout.cancel(customTimeout);

The same applies to “$interval()”.

To disable a watch, just call it.

.$watch() returns a deregistration function that we store to a variable

var deregisterWatchFn = $rootScope.$watch(‘someGloballyAvailableProperty’, function (newVal) {
  if (newVal) {
    // we invoke that deregistration function, to disable the watch
    deregisterWatchFn();
    ...
  }
});