Zone Profiling

Example of profiling asynchronous methods using zone.

by Michael Hunziker

HTML

<div>
    <button id="myBtn">Populate</button>
    <span id="myData">Nothing</span>
</div>

JavaScript

// 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";
    var btn = document.getElementById("myBtn"),
        data = document.getElementById("myData");
    btn.addEventListener("click", function() {
        zone.marker = "click";
        data.innerHTML = "Initializing...";
        setTimeout(function() {
            zone.marker = "timeout";
            data.innerHTML = "Done.";            
        }, 2000);        
    });    
};

// 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: Zone,

  fork: function (locals) {
    return new Zone(this, locals);
  },

  bind: function (fn) {
    var zone = this.fork();
    return function zoneBoundFn() {
      var result = zone.run(fn, this,...