How to check if the digest cycles have stabilized (aka "Has angular finished compilation?")

All we need is an easy explanation of the problem, so here it is.

tl;dr: The initial question was “How to trigger a callback every digest cycle?” but the underlying question is much more interesting and since this answers both, I went ahead and modified the title. =)

Context: I’m trying to control when angular has finished compiling the HTML (for SEO prerendering reasons), after resolving all of its dependencies, ngincludes, API calls, etc.
The “smartest” way I have found so far is via checking whether digest cycles have stabilized.
So I figured that if I run a callback each time a digest cycle is triggered and hold on to the current time, if no other cycle is triggered within an arbitrary lapse (2000ms), we can consider that the compilation has stabilized and the page is ready to be archived for SEO crawlers.

Progress so far: I figured watching $rootScope.$$phase would do but, while lots of interactions should trigger that watcher, I’m finding it only triggers once, at the very first load.

Here’s my code:

app.run(function ($rootScope) {
  var lastTimeout;
  var off = $rootScope.$watch('$$phase', function (newPhase) {
    if (newPhase) {
      if (lastTimeout) {
        clearTimeout(lastTimeout);
      }
      lastTimeout = setTimeout(function () {
        alert('Page stabilized!');
      }, 2000);
    }
  });


Solution: Added Mr_Mig‘s solution (kudos) plus some improvements.

app.run(function ($rootScope) {
  var lastTimeout;
  var off = $rootScope.$watch(function () {
    if (lastTimeout) {
      clearTimeout(lastTimeout);
    }
    lastTimeout = setTimeout(function() {
      off(); // comment if you want to track every digest stabilization
      // custom logic
    }, 2000);
  });
});

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I actually do not know if my advice will answer your question, but you could simply pass a listener to the $watch function which will be called on each iteration:

$rootScope.$watch(function(oldVal, newVal){
    // add some logic here which will be called on each digest cycle
});

Have a look here: http://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply