Zone Profiling with Angular

Example of profiling asynchronous methods using zone.

by Jeremy Likness

HTML

<div>
    <button id="myBtn" ng-click="populate()">Populate</button>
    <span id="myData">{{data}}</span>
</div>

JavaScript

// read the blog about this here: 
// http://bit.ly/zoneperf 

// this updates the example to manually bootstrap angular within a zone

// run this with console open to see the performance metrics
// the zone is initialized/forked at the bottom of the code

var main = function() {
    zone.marker = "main";
    angular.module('myApp', []).run(function($rootScope, $timeout){
        zone.marker = "module run";
        $rootScope.populate = function() {
            zone.marker = "click";
            $rootScope.data = "Initializing...";
            $timeout(function() {
                zone.marker = "timeout";
                $rootScope.data = "Done";
            }, 2000);
        };
    });
    angular.bootstrap(document, ['myApp']);           
};

// profile zone from Zone.js examples (modified for this example)
var profilingZone = (function () {
    var time = 0,
        // use the high-res timer if available
        timer = performance ?
                    performance.now.bind(performance) :
                    Date.now.bind(Date);
    return {
        marker: "?",
      onZoneEnter: function () {
        this.originalStart = this.originalStart || timer();
        this.start = timer();
        console.log("Entered task");
      },
      onZoneLeave: function () {
        var diff = timer() - this.start,
            totalDiff = timer() - this.originalStart;
        console.log("Exited task " + zone.marker + " after " + diff);
        time += diff;
          console.log("Total active time: " + time);
          console.log("Total elapsed time: " + totalDiff);
      },
      reset: function () {
        time = 0;
      }
    };
  }());

// this is from https://github.com/angular/zone.js
function Zone(parentZone, data) {
  var zone = (arguments.length) ? Object.create(parentZone) : this;

  zone.parent = parentZone;

  Object.keys(data || {}).forEach(function(property) {
    zone[property] = data[property];
  });

  return zone;
}


Zone.prototype = {
  constructor:...