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

Technology CommunityCategory: AngularJSHow do you reset a “timeout”, “interval()”, and disable a “$watch()”?
VietMX Staff asked 3 years ago

To reset a timeout and/or $interval, assign the result of the function to a variable and then call the .cancel() function:

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

$timeout.cancel(customTimeout);

To disable $watch(), we call its deregistration function. $watch() then returns a deregistration function that we store to a variable and that will be called for cleanup:

var deregisterWatchFn = $scope.$on('$destroy', function() {
  // we invoke that deregistration function, to disable the watch
  deregisterWatchFn();
});