Monday, July 24, 2017

Log execution time of function/Ajax Call



Initialization of the variable to store all logs in controller

$rootScope.timeSlots = {};



//Function to create object with eventname , start time, end time using ID
$scope.logEvent = function(Eventid, EventName, isEnd){
    if(isEnd == false){
         $rootScope.timeSlots[Eventid] = {
            "name": EventName,
            "startDate":new Date().getTime()
         };
    } else {
        $rootScope.timeSlots[Eventid]["endDate"] = new Date().getTime();
    }
};
Log starting time 
$scope.logEvent("function1","Function1 start Time", false);
Log end time
$scope.logEvent("function1","", true);

Html template code:
<div ng-repeat = "time in timeSlots">
    <p>{{time.name}} - <span  ng-bind="time | getDiff">
    </span></p>
</div>

Filter code to calculate time and display it on UI
app.filter("getDiff", function() {
  return function(time) {
    var startDate = new Date(time.startDate);
    var endDate = new Date(time.endDate);
    var milisecondsDiff = endDate - startDate;

      var timeTxt = "";
      if(Math.floor(milisecondsDiff/(1000*60*60)) != 0){
        timeTxt += Math.floor(milisecondsDiff/(1000*60*60)) + " hr ";
      }
      if(Math.floor(milisecondsDiff/(1000*60))%60 != 0){
        timeTxt += (Math.floor(milisecondsDiff/(1000*60))%60)  + "min";
      }
      if(Math.floor(milisecondsDiff/1000)%60 != 0){
        timeTxt += (Math.floor(milisecondsDiff/1000)%60) +" Sec ";
      }
      if(Math.floor(milisecondsDiff%1000) != 0){
        timeTxt += (Math.floor(milisecondsDiff%1000)) +" ms";
      }
      return timeTxt;
  }
});