dariofarzati
dariofarzati

Reputation: 8646

Why is this code not reaching the 10-cycle $digest loop limit?

According to http://angular-tips.com/blog/2013/08/watch-how-the-apply-runs-a-digest/:

This is the dirty-checking. Now that all the $watch have been checked there is something else to ask: Is there any $watch that has been updated? If there is at least one of them that has changed, the loop will fire again until all of the $watch report no changes. This is to ensure that every model is clean. Have in mind that if the loop runs more than 10 times, it will throw an exception to prevent infinite loops.

From my understanding, if I put this in my view:

{{ date }}

and this in my controller

$interval(function () { 
    $scope.date = new Date(); 
}, 1)

what should happen is:

  1. $interval invokes my fn and triggers a $digest loop;
  2. the $watcher for date reports its value has changed;
  3. no more $watchers, but due to "dirty" state, $watchers are asked again;
  4. the $watcher for date reports its value has changed again (since it's being changed each 1ms)
  5. so on until 10 cycles, then error

but this is not the case. Code runs fine, view is updated all the time and no errors are thrown.

Why?

Upvotes: 2

Views: 557

Answers (1)

Sunil D.
Sunil D.

Reputation: 18193

You never hit the limit of 10 digest cycles because each time $interval runs it starts a new cycle.

Check out the section titled "Integration with the browser event loop" in the Angular developer guide.

In your scenario, $interval is generating a new browser event. The event results in Angular's $apply() function being run. This process completes. Then on the next interval, a new event is generated and the process starts over.

Angular's event loop

Upvotes: 3

Related Questions