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

1

5

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);
  });
});
Nicotine answered 26/2, 2014 at 10:58 Comment(0)
M
3

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

Molton answered 26/2, 2014 at 14:43 Comment(3)
Thanks! It hadn't occurred to me that I can use the watcher as a trigger... Works like a charm! =)Nicotine
Note that it will fire once for each $digest, not once for each $digest cycle. One cycle can call $digest multiple times.Visually
I'm aware. Wish I could come up with something more efficient... Thanks though!Nicotine

© 2022 - 2024 — McMap. All rights reserved.