Design & Download
Your JS Library
in Seconds!!!

Snippet: time() - Timing Function Execution

Written by Christopher West (cwest) on December 12, 2015.
Creates a wrapper which executes the function and indicates the timing information of the execution.
function time(fn, times) {
  if (typeOf(times, 'Array')) {
    var arr = times;
    times = function(timeElapsed, start, end, returnValue, args, context) {
      arr.push(extend(Object(timeElapsed), {
        start: start,
        end: end,
        returnValue: returnValue,
        context: context,
        arguments: args
      }));
    };
  }
  return function() {
    var start = new Date,
        ret = fn.apply(this, arguments),
        end = new Date;
    times.call(fn, end - start, start, end, ret, arguments, this);
  };
}

time(...) API Documentation

Description

Creates a wrapper which executes the function and indicates the timing information of the execution.

Parameters

  1. fn {Function}:
    The function to wrap so as to properly get the starting time and ending time of its execution.
  2. times {Array|Function}:
    • Array.<{ start: number, end: number, returnValue: *, arguments: Arguments, context: * }
      If it is an array, a new timing data Number object will be appended to it after every execution of the wrapped function. The number object's value will represent the amount of time that elapsed in milliseconds executing the function. The timing data Number object will have the following property keys set: start, end, returnValue, arguments, and context.
    • function(this: fn, elapsed, start, end, returnValue, args, context)
      If it is a function, after every execution of fn(), this function will be called with the following arguments: : start, end, returnValue, arguments, and context. The context (or this) will be a reference to fn().

Returns

Returns the wrapped function. This function, when executed, will pass the context object and the arguments as is to fn() and the return value will be that of fn().