0

I have the following code:

function myFunction(elem){
console.log(elem);
}

scope.$watch(function(){
  return obj.width;
}, function(valTo, valFrom) {
  myFunction(valTo);
});

But I have question on doing something like this. The myFunction function is running once the watcher triggers an event. But if the watcher triggers multiple events, does it maintain the function running on all those events or does it stop everything on every previous events once the new event kicks in?

gespinha
  • 7,968
  • 16
  • 57
  • 91
  • Question is unclear, if obj.width changes three times myFunction() will fire three times. – Dennis Mar 24 '16 at 11:34
  • from Angular documentation: The watchExpression is called on every call to $digest() and should return the value that will be watched. (watchExpression should not change its value when executed multiple times with the same input because it may be executed multiple times by $digest(). That is, watchExpression should be idempotent. – Oron Bendavid Mar 24 '16 at 11:53
  • @OronBen-David So, if I have a function that runs along with the page, If it is called three times on the watch, does it keep three instances of that function running? – gespinha Mar 24 '16 at 11:57
  • Yes - again from Angular documentaion: he $digest() keeps calling the watchers until no more listeners are firing. This means that it is possible to get into an infinite loop. This function will throw 'Maximum iteration limit exceeded.' if the number of iterations exceeds 10. – Oron Bendavid Mar 24 '16 at 12:05
  • @OronBen-David how do I cancel a funcion that was run inthe previous watchers? – gespinha Mar 24 '16 at 12:11
  • 1
    please see the following example for how clearing $watch: http://stackoverflow.com/questions/14957614/angularjs-clear-watch – Oron Bendavid Mar 24 '16 at 12:17
  • Thanks for the help :) – gespinha Mar 24 '16 at 12:26

0 Answers0